Pavunkumar
Pavunkumar

Reputation: 5335

integer index incrementation in array

I have one doubt in the following snippet. Actually I am initializing all the array index to zero in following code, but this for loop is going infinitely. I found reason that we are trying to access the 26th index of array, so that value gets initialized to zero again since there is 0 to 25 index. So the for loop is going infinitely. Explain if any one the actual reason behind this stuff.

int array[26];
int i; 
for (i = 0; i <= 26; i++) 
    array[i]= 0;

Upvotes: 0

Views: 2613

Answers (3)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385104

I found reason that we are trying to access the 26th index of array, so that value gets initialized to zero again since there is 0 to 25 index. So the for loop is going infinitely.

The reason is that your loop variable i goes from 0 to 26 inclusive. But there is no array[26].. only array[0] to array[25] (which is a total of 26 elements).

You are invoking undefined behaviour by writing to array[26]; it just so happens in your execution run that i was laid out just after array in memory, and you were accidentally writing 0 to i due to the erroneous write. This may have caused an infinite loop.

Instead write:

int array[26];
int i;
for (i = 0; i < 26; i++) {
   array[i] = 0; 
}

Upvotes: 0

red1ynx
red1ynx

Reputation: 3775

Maybe i is located after array in the memory and it become 0 when i=26 in the loop. I.e. &array[26] == &i.

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318488

You have to use i < 26; otherwise you exceed the array bounds.

Due to the layout of the stack on most systems array[26] will point to the memory used for i which results in the loop starting again since you loop body is setting i to 0 instead of an appropriate array element.

Note that you can simply use int array[36] = { 0 }; to create the array with all elements being set to 0.

Upvotes: 10

Related Questions