user3520616
user3520616

Reputation:

array always returns stupid things

I don't know why it doesn't work...

I have an array

int point[6][6][1]

and I have a while loop:

int i = 0;
while (point[i + 1][0][0] > 0) {
   i++;
}

return i;

If I have 3 points declared

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

TotalNumberOfPoints(point)

The while loop ends with i being 4.

If I have 4 points declared

point[1][0][0] = 1;
point[2][0][0] = 2;
point[3][0][0] = 3;
point[4][0][0] = 4;

It returns 4.

If I have 5 points declared

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

It returns 7.

Why is this? And how can I fix it?

Upvotes: 0

Views: 91

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726929

The problem is that your loop may produce undefined behavior when the last point (i.e. the one with the first index of 5 is set, because the loop is not checking i for i < 5.

Here is how you can fix it:

while(i < 5 && point[i + 1][0][0] > 0] {
   i++;
}

The reason you compare i to 5, not to 6, is that you proceed to checking point[i+1], so i needs to be less than 5, not 6.

Upvotes: 3

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145419

Try to zero-initialize your array.

int point[6][6][1] = {};

By the way, note that

  • For correctness you need to ensure that there's a 0 at the end of the array, or stop the looping some other way (e.g. use a counter).

  • A dimension of size 1 is not really useful.

  • You can use std::vector to create a dynamically sized array.

Upvotes: 0

Rakib
Rakib

Reputation: 7625

You should initialize the array while declaring it

int point[6][6][1]={0};

Otherwise it will contain garbage value which may not be zero, making your loop condition false.

And your loop should be

while(i<5 && point[i+1][0][0] > 0) {
   i++;
 }

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117981

You can't just do this

while(point[i + 1][0][0] > 0] {
   i++;
}

What happens when i = 6? You will get undefined behavior. It doesn't know the array just started indexing out of bounds, so the "element at index 7" may very well be greater than 0, or less, or whatever happens to be there.

Also your array is uninitialized so the value at each element may be arbitrary.

Upvotes: 0

Related Questions