Question

That is the code:

point [1][2][1] = 3;
cout << point[1][2][1] << endl;
point [1][3][0] = 4;
cout << point[1][2][1] << endl;

And that is what the console says when I run the application:

3
4

If I change to

point[1][3][0] = 5;

it says

3
5

How can I remove this annoying error? I cant continue that way.

Was it helpful?

Solution

When your variable is declared as

int point[100][100][1];

Then the valid indexes are respectively 0...99, 0...99, 0...0.

Your access to point[1][2][1] is therefore quite inappropriate. Depending on which index you make out of range, you might access an area outside the array entirely, or in a different slice of the array.

If you really want to access array elements arbitrarily, then I suggest you discard the triple-subscript notation and use:

int point[m][n][p];
int* p = &point[0][0][0];
p[x*n*p + y*p + z]

Now you are in control over row-major vs column-major access, and any computation that yields an offset less than m*n*p is valid.

Note that in your case m=n=100 and p=1, so that point[1][3][0] is p[1*100*1 + 3*1 + 0] = p[103] and also point[1][2][1] is p[1*100*1 + 2*1 + 1] = p[103]. So both really are the same location.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top