Skip to main content

Compile time initialization of arrays

Short answer

Compile-time initialization of 2D: int m[2][3] = {{1,2,3},{4,5,6}}; row-wise; column size mandatory. For 1D, if size given and fewer initializers, remainder set to 0; if size omitted, compiler counts initializers; excess initializers cause error.

Explain with an example for compile time initialization of 2D array. Describe how compiler manages according to the number of initializers and size of an array given by a user in case of 1D array.

Compile time initialisation of a 2D array

The values are given in the declaration, so the compiler stores them when the program is compiled/loaded, and no input is needed at run time.

int m[2][3] = {{1, 2, 3}, {4, 5, 6}};

Each inner brace is one row. m[0][1] is 2 and m[1][2] is 6. It can also be written in one list: int m[2][3] = {1, 2, 3, 4, 5, 6};, filled row by row. The row size may be omitted, but the column size is compulsory: int n[][2] = {{1, 2}, {3, 4}, {5, 6}}; gives 3 rows.

How the compiler handles the initialiser count and array size (1D)

  1. Size given and initialisers equal: all elements get the given values.
  2. Fewer initialisers than size: the given values go to the first elements and the remaining elements are set to 0, e.g. int b[6] = {1, 2}; gives 1 2 0 0 0 0.
  3. Size omitted: the compiler counts the initialisers and sets the size, e.g. int a[] = {5, 10, 15, 20}; creates 4 elements.
  4. More initialisers than size: error/warning (excess elements); not allowed.
#include <stdio.h>

int main(void)
{
    int m[2][3] = {{1, 2, 3}, {4, 5, 6}};   /* 2D, fully initialised */
    int a[]  = {5, 10, 15, 20};             /* size omitted -> 4 */
    int b[6] = {1, 2};                      /* rest become 0 */
    int n[][2] = {{1, 2}, {3, 4}, {5, 6}};  /* only first size may be omitted */

    printf("sizeof a = %zu bytes (%zu elements)\n", sizeof a, sizeof a / sizeof a[0]);
    printf("b: ");
    for (int i = 0; i < 6; i++)
        printf("%d ", b[i]);
    printf("\nm[1][2] = %d, rows of n = %zu\n", m[1][2], sizeof n / sizeof n[0]);
    return 0;
}

Output:

sizeof a = 16 bytes (4 elements)
b: 1 2 0 0 0 0 
m[1][2] = 6, rows of n = 3

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →