Suppose I define two arrays, each of which have 2 elements (for theoretical purposes):
char const *arr1[] = { "i", "j" };
char const *arr2[] = { "m", "n" };
Is there a way to define a multidimensional array that contains these two arrays as elements? I was thinking of something like the following, but my compiler displays warnings about incompatible types:
char const *combine[][2] = { arr1, arr2 };
The only way it would compile was to make the compiler treat the arrays as pointers:
char const *const *combine[] = { arr1, arr2 };
Is that really the only way to do it or can I preserve the type somehow (in C++, the runtime type information would know it is an array) and treat combine
as a multidimensional array? I realise it works because an array name is a const pointer, but I'm just wondering if there is a way to do what I'm asking in standard C/C++ rather than relying on compiler extensions. Perhaps I've gotten a bit too used to 开发者_StackOverflow社区Python's lists where I could just throw anything in them...
No. First, this
char const *combine[][2] = { arr1, arr2 };
cannot work, because arr1
and arr2
cannot be used to initialize an array. But this:
char const *arr1[] = { "i", "j" };
char const *arr2[] = { "m", "n" };
char const *(*combine[])[2] = { &arr1, &arr2 };
works as well as this
char const *arr1[] = { "i", "j" };
char const *arr2[] = { "m", "n" };
char const *combine[][2] = { {"i", "j"}, {"m", "n"} };
精彩评论