Multiple indexes missing with segfault for loop

The output of the application (below) is as follows:

Item index number: 0 Item content: 22
Item index number: 1 Item content: 22
Item index number: 2 Item content: 22
Item index number: 3 Item content: 22
Item index number: 4 Item content: 22
Item content: 22 Item index number: 22 Item Content: 134513712

Why are index entries labeled 5-21 missing? I understand that this code can do segfault to the limit of an overflowed array, it is designed for this, I am not interested in why this code is bad, just why some indexes are skipped.

#include <stdio.h>
int main(){

int array[5];

int i;
for(i=0; i<10; ++i){
    array[i] = 22;
    printf("Element index number: %d Element contents: %d\n", i, array[i]);
}
return 0;
}
+5
5

, [5], i. , .

,

5

int array[5];

, - . [] , . :

  • array [0] 0 ints ""
  • array [1] - 1 ints "array" ...
  • array [4] - 4 ints "array" ( int )

,

  • array [5] - 5 ints ""

C , . "i" [5] , , [5] - i.

[5], i, 22, 22. , 22, [i] [22]. , ; , .

+7

, "undefined ". , , "i" .

, , Java #, C , (, segfault) malloced. . , , .

+9

@Doug , .

[5] , , 6 : array [0], array [1],... array [4], i.

5, [i] , i. 22. , = 22, .

[i] [22], stck; .

+2

Most likely, the storage for the local variable "i" is immediately after the "array" on the stack, therefore & array [5] == & i, which means that you assign 22 "i" when you assign 22 to the array [5] .

0
source

You declared an array of 5 integers, but your for loop writes the values ​​to 10 records.

Change

int array[5];

to

int array[10];
-1
source

All Articles