Michel Jord Michel Jord - 3 months ago 6
C Question

Is it the correct way to initialize array?

Here is one not-so-common way of initializing the array:

int a[3] = {[2] 5, [0] 10, [1] 15};


Used this array in the program,

#include <stdio.h>

int main() {
//code
int a[3] = {[2] 5, [0] 10, [1] 15};
printf("a[0] = %d a[1] = %d a[2] = %d\n", a[0], a[1], a[2]);
return 0;
}


Output:

a[0] = 10 a[1] = 15 a[2] = 5


Online Compiler Link:
http://code.geeksforgeeks.org/4onQAI

So, I have a question:

Is it the correct way to initialize array?

Answer

Close. The correct way is as follows:

int a[3] = {[2] = 5, [0] = 10, [1] = 15};

This is a designated initializer, which allows you to initialize specified elements. Any elements not specified are set to 0.

This is specified in section 6.7.9 of the C standard.

The syntax you show is a non-standard extension supported by some compilers.

Comments