Bob Bob - 3 months ago 11
C Question

Initializing part of a multidimensional array with a list of constants in C

Say I have an array

int A[2][2];


and I want to initialize only the first row with a list of constants like so

A[0] = {
1,
2
};


Unfortunately the compiler returns.

error:

expected expression before '{' token_.


Although this example is small, think big. I know there are some obtuse ways of doing it but it would shock me if there wasn't an efficient solution.

Answer

Initializers do not work like that. You should initialize it at the time of declaration as

int A[2][2] = { {1, 2} };        // Rest elements will be initialized to 0

or using designated initializer

int A[2][2] = { [0] = {1, 2} };  // C99 and later