array returns weird values

Hi guys, i'm new to C++ OOP and i'm not sure what's wrong with my codes. I get weird values from the array whenever i call them out.

pointtwod.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class PointTwoD
{
 	private:
 		int xcord,ycord;
		float civIndex;
		LocationData locationdata;

 	public:
        	PointTwoD();

        	PointTwoD(int, int, string, int, int, float, float, float);
	
		string toString();
		
		void displayPointdata();

		//set/mutator function
		void setxcord(int);
		void setycord(int);

		//get/accessor function
		int getxcord();
		int getycord();
	
		void storedata(int, int, float);

};


pointtwod.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//declaring array
void PointTwoD::storedata(int xcord, int ycord, float civIndex)
{
	int xord[5];
	int yord[5];
	float civ[5];
	int i=0;
	int size = sizeof(xord)/sizeof(xord[0]);
	
	for(i=0;i<size;i++)
	{
		if(civ[i] == 0)
		{
			civ[i] = locationdata.getCivIndex();
		}
                if(xord[i] == 0)
		{
			xord[i] = xcord;
		}
                if(yord[i] == 0)
		{
			yord[i] = ycord;
		}
	}

	for(i=0;i<size;i++)
	{
		if(civ[i] != 0)
		{
			cout << "civ index is: " << civ[i] << endl;
		}
                if(xord[i] != 0)
		{
			cout << "x axis is: " << xord[i] << endl;
		}
                if(yord[i] != 0)
		{
			cout << "y axis is: " << yord[i] << endl;
		}
	}
	
}


when I cout the xcord, ycord and locationdata.getCivIndex() i could get the value I want.. only when it comes to array.
Last edited on
It's possible that since you didn't initilalise your arrays they're filled with garbage. Therefore your "== 0" tests fail and the garbage remains. Try initialising them all to 0 and see if this helps.
1
2
3
	int xord[5] = {0};
	int yord[5] = {0};
	float civ[5] = {0.0};
In this function, you create 3 arrays: xord, yord, and civ.

You do not initialize ANY of them. Therefore they contain random garbage. (Remember, you are declaring them inside the function, which means they are recreated and destroyed every time the function is called -- they are not part of the class).

On lines 12, 16, 20, you proceed to check to see if the elements in your array are 0... but since you never set any elements in the array... these comparisons are meaningless.

Same with the loop on lines 26-40

I'm not sure what the goal of this function was.
for

1
2
3
4
if(civ[i] == 0)
{
	civ[i] = locationdata.getCivIndex();
}


it's to check if the location of the memory is empty, if it's empty than the value will be stored in the location

so in order to initialize the array is this what i got to do?
void PointTwoD::storedata(int xord, int yord, int xcord, int ycord, floatciv, float civIndex)
Last edited on
Topic archived. No new replies allowed.