1

guyz, today I got a serious confusion (well, for me at least). I was declared an array, with following property:

      int arr[0][1] = {1,2,3,4,5,6 ... };

while doing this, i was getting this warning:

    warning: excess elements in array initializer.

while printing this code, i was getting, some garbage value in every index. after that, i was trying with following snippets,

    int arr[][1] = {1,2,3,4,5,6,7,8,9};

and strangely, i was getting no warning and no error. and when i was executing with following code:

     #include <stdio.h>
    int main() {
   int t[][1] = {1,2,3,4,5,6,7,8,9};
        for(int i=0; i<9; i++){
         for(int j=0; j<9; j++)
            printf("%i ",t[i][j]);
         printf("\n");
        }   
    return 0;
     }

i was getting this result:

    1 2 3 4 5 6 7 8 9
    2 3 4 5 6 7 8 9 0
    3 4 5 6 7 8 9 0 8
    4 5 6 7 8 9 0 7 3
    5 6 7 8 9 0 6 4 13247168
    6 7 8 9 0 5 5 13247168 0
    7 8 9 0 4 6 13247168 0 4199400
    8 9 0 3 7 13247168 0 4199400 0
    9 0 2 8 13247168 0 4199400 0 0

Now this is become a serious problem and confusion for me to understand. Help me if you know the reason behind. Thank you.

Papai from BEKOAIL
  • 1,469
  • 1
  • 11
  • 17

1 Answers1

3

when imposing the first dimension to the compiler, since the compiler sees that you're trying to initialize with more data than the dimension can contain, you get a warning.

Now with int t[][1] = {1,2,3,4,5,6,7,8,9};, you're letting the compiler compute the size automatically. But that doesn't mean there will be a run-time check for the bounds.

Once compiled without warnings, there is no run-time to check that a dynamic access out of bounds is catched. What you're experiencing at run-time is just undefined behaviour of reading/writing out of bounds.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219