What is this syntax for initializing 2D array?

This is technically C and I understand this is a common way to initialize a 2D array:
 
 const char* str_arr[] ={{"lol", "hehe"}, {"hehe", "hehehe"}};


However, below one can also specify indices in array initialization. I've never seen something like this before. Can someone explain?
 
 int aaa[2][3] = {[0] = {6,2,3}, [1]={2,3,4}};
Last edited on
However, below one can also specify indices in array initialization. I've never seen something like this before. Can someone explain?

Designated initializers. This particular syntax is allowed in C but not C++.

C++: https://en.cppreference.com/w/cpp/language/aggregate_initialization
C: https://en.cppreference.com/w/c/language/initialization
Last edited on

to initialize a 2D array:

 
const char* str_arr[] = {"lol", "hehe"};



That initialises a 1 D array of pointers to char.
Hello RicoJ,

For a 2D array this is what I like to do:
1
2
3
4
5
6
7
8
9
10
11
12
// <--- Can be defined as a global variable to the file if the file has more than 1 function.
// The variable names are your choice, but I find these work well.

constexpr unsigned int MAXROWS{ 2 }, MAXCOLS{ 3 };  // <--- Or just "unsigned" will work.


int aaa[MAXROWS][MAXCOLS]
{
    {6, 2, 3},
    {2, 3, 4}
};


Andy
Yes for C++ - but the original question concerns c.
My bad. I misunderstood the 1st 2 lines of OP's post

Andy
Thanks @mbozzi, this is designated initialization: https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html

Topic archived. No new replies allowed.