Search code examples
arraysc

Why in C can I initialize more values than the size of an array?


This array has a size of 1 but I can initialize it with these values, then I can even set more values after I instantiate the array and it still works. I don't understand why.

int array[1] = {12,2,12,12,12,31};

printf("%d\n",array[1]);
printf("%d\n",array[0]);

array[1] = 1;
array[8] = 3;
printf("%d\n",array[1]);// 1 It works. Why?
printf("%d\n",array[8]);// 3 It works. Why?

Solution

  • In C, arrays don't have in-built bounds checking. Accessing beyond the declared bounds of an array doesn't immediately cause your program to crash. Instead, it is called undefined behaviour. Undefined behaviour means the standard doesn't define what must happen, so the program might seem to "work", or it might crash or corrupt memory.

    When you do this:

    array[1] = 1;

    array[8] = 3;

    You are writing to memory regions outside the allocated space for the array. The compiler doesn't stop you from doing this, and if those memory regions aren't critical to the running of your program (or if you're lucky), your program may appear to run normally. But this is just luck, and unpredictable behaviour could happen at any time.