WadeC
WadeC

Reputation: 11

Array not producing correct output

I have a problem with assigning variables to an array from different functions. I have two functions that produce different numbers. I then want to assign those numbers to a private array in the same class. When I do this the array returns large negative numbers.

// Array.h
class Array {
private:   
     int W = A;   
     int Q = B; 
     int sum[2] = {W, Q};
public:   
     int A;    
     int B;    
     int num1();    
     int num2();   
     int add();
};


// Array.cpp
#include<iostream>
using namespace std;
#include "Array.h"

int Array::num1()
{
    int x = 3;
    int y = 4;
    A = x + y;
    cout << A << endl;
    return A;
}

int Array::num2()
{
    int x = 2;
    int y = 5;
    B = x + y;
    cout << B << endl;
    return B;
}

int Array::add()
{
    for(int i = 0; i < 2; i++)
    {
        cout << sum[i] << endl;
    }
    return 0;
}


// main.cpp
#include <iostream>
#include "Array.h"

int main() {
    Array sumTotal;
    sumTotal.num1();
    sumTotal.num2();
    sumTotal.add();
    return 0;
}

Upvotes: 1

Views: 60

Answers (2)

Ivan Molnar
Ivan Molnar

Reputation: 11

Problem is here:

int W = A;
int Q = B;
int sum[2] = { W, Q };

You are just coping value from A and B to W and Q. And later when you set A and B, those changes are not reflected to W or Q. Thus leaving W and Q uninitialized.

Note: consider researching more about C++ topic in field of arrays, pointers and references.

This is modified code that works ok:

#include <iostream>


using namespace std;

class Array {
private:
   int sum[2];
public:
   int num1();
   int num2();
   int add();
};


int Array::num1()
{
   int x = 3;
   int y = 4;
   sum[0] = x + y;
   cout << sum[0] << endl;
   return sum[0];
}

int Array::num2()
{
   int x = 2;
   int y = 5;
   sum[1] = x + y;
   cout << sum[1] << endl;
   return sum[1];
}

int Array::add()
{
   for (int i = 0; i < 2; i++)
   {
      cout << sum[i] << endl;
   }
   return 0;
}


int main(int argc, char** argv)
{
   Array sumTotal;
   sumTotal.num1();
   sumTotal.num2();
   sumTotal.add();

   return 0;
}

Upvotes: 1

cigien
cigien

Reputation: 60440

The reason you are getting garbage values (large negative numbers, in your case) is that you are not initializing A or B to any meaningful values, and then you are not updating sum when you call num1, or num2.

You should initialize A and B to something meaningful in the class, or at least default initialize it.

Then you need to update sum in num1, like this:

int Array::num1()
{
    int x = 3;
    int y = 4;
    A = x + y;
    sum[0] = A;        // <- add this
    cout << A << endl;
    return A;
}

and do a similar thing inside num2.

You also have 2 variables W, and Q inside your class which don't seem to serve any purpose. Apart from the issue with initializing them incorrectly with garbage values, you don't even need them; you could just use A, and B instead.

Upvotes: 0

Related Questions