What is this syntax for initializing 2D array?

Jul 16, 2021 at 1:27am
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 Jul 16, 2021 at 5:29pm
Jul 16, 2021 at 1:57am
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 Jul 16, 2021 at 1:58am
Jul 16, 2021 at 9:02am

to initialize a 2D array:

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



That initialises a 1 D array of pointers to char.
Jul 16, 2021 at 11:18am
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
Jul 16, 2021 at 11:36am
Yes for C++ - but the original question concerns c.
Jul 16, 2021 at 12:45pm
My bad. I misunderstood the 1st 2 lines of OP's post

Andy
Jul 16, 2021 at 5:33pm
Thanks @mbozzi, this is designated initialization: https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html

Topic archived. No new replies allowed.