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

  • The original code line:

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

    In standard C (as per ISO/IEC 9899 standard), this is a constraint violation. A constraint violation means the code is simply invalid and does not conform to the standard. According to the C standard (C17, §6.7.9 Initialization):

    "No initializer shall attempt to provide a value for an object not contained within the entity being initialized."

    Thus, the compiler must issue a diagnostic (at least a warning, typically an error) for this code. The standard explicitly forbids providing more initializers than there are elements in the array, making this particular snippet non-standard and invalid.

    The separate issue, demonstrated by:

    array[1] = 1;
    array[8] = 3;
    

    In standard-compliant code (assuming the array was properly initialized), accessing or writing behind array bounds is undefined behaviour (UB). UB means the standard imposes no requirements on the program's behaviour; it could seemingly "work", crash, corrupt memory, or exhibit any other unpredictable behaviour.