Incorrect values displayed for an array

Hello,

I have the following code:

header:
1
2
3
4
5
6
7
8
9
10
#pragma once

class num
{
private:
	int no[3][3];
public:
	void setVal();
	int getVal(int i, int j);
};


source.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 #include "num.h"

void num::setVal()
{
	for (int i = 0; i < 4; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			no[i][j] = 0;
		}
	}
}

int num::getVal(int x, int y)
{
	return no[x][y];
}


and main:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdlib.h>
#include "num.h"
#include <iostream>

using namespace std;

int main()
{
	num number;
	for (int j = 0; j < 4; j++)
	{
		for (int i = 0; i < 4; i++)
		{
			cout<<number.getVal(i, j)<<" ";
		}
	}

	system("pause");
    return 0;
}


Instead of displaying 0 multiple times, the program displays the value -858993460

What's going wrong?
1
2
3
4
(0 < 4) == true
(1 < 4) == true
(2 < 4) == true
(3 < 4) == true

How many trues was there?

int foo[3];
How many elements in the array?
Still not working after declaring no[4][4]. Same output is displayed.

Instead of displaying 0 multiple times, the program displays the value -858993460

That's because you haven't called setVal() yet, so your array is filled with junk values.

I would recommend doing what you did in setVal(), in the constructor, because that's what the constructor is for - initialising values.
integralfx,

You could either put the code of setVal() in the constructor or just call setVal() in main before the print loop. After that I had to change every for loop to be < 3 and then it worked. Remember that arrays start with 0 not 1. So, your loops are making the last element of the array being no[3][3] when the max should be no[2][2],

When I changed all the for loops to be i & j < 3 everything worked fine.

Hope that helps,

Andy
Topic archived. No new replies allowed.