Reputation: 19043
i need something like this
const char **nodeNames[] =
{
{"RootNode", "Reference", "Node_1", "Node_2", "Node_3"},
{"RootNode", "Hips", "Node_1", "Node_2", "Node_3"},
{"RootNode", "Heviest", "Node_1", "Node_2", "Node_3"},
};
but with previous declaration, i got an error.
And how can i reference to it in code?
Upvotes: 0
Views: 7592
Reputation: 55395
Looks like you want a two dimensional array of const char*
:
const char *nodeNames[][5] =
{ // ^^ this dimension can be deduced by the compiler, the rest not
{"RootNode", "Reference", "Node_1", "Node_2", "Node_3"},
{"RootNode", "Hips", "Node_1", "Node_2", "Node_3"},
{"RootNode", "Heviest", "Node_1", "Node_2", "Node_3"}
};
Note that you need to explicitly specify all but the major dimension's size.
This doesn't behave exactly like a 3D array of chars because your strings are not all of the same size. I trust you're aware of that and you won't for example dereference nodeNames[0][2][7]
, which would go beyond the end of "Node_1"
.
Upvotes: 3
Reputation: 129374
Depends a little bit on what you want. This will give you a 2D array of strings:
const char *nodeNames[][20] =
{
{"RootNode", "Reference", "Node_1", "Node_2", "Node_3"},
{"RootNode", "Hips", "Node_1", "Node_2", "Node_3"},
{"RootNode", "Heviest", "Node_1", "Node_2", "Node_3"},
};
This will give you an array of pointers to an array of strings.
const char *node1[] = {"RootNode", "Reference", "Node_1", "Node_2", "Node_3"};
const char *node2[] = {"RootNode", "Hips", "Node_1", "Node_2", "Node_3"};
const char *node3[] = {"RootNode", "Heviest", "Node_1", "Node_2", "Node_3"};
const char **nodeNames2[] =
{
node1,
node2,
node3,
};
Note that the two are subtly different, in that the first is stored within the array (so there is a contiguous storage of 3 * 20 pointers to the strings), where the second only stores the address to the first pointer in the array of pointers, which in turn point to the string. There is no contiguous storage, only three pointers.
In both cases, the pointers may be the same value, since the three instances "Node_1"
may be represented by a single string.
For a proper 3D array of char:
const char nodeNames3[3][5][12] =
{
{"RootNode", "Reference", "Node_1", "Node_2", "Node_3"},
{"RootNode", "Hips", "Node_1", "Node_2", "Node_3"},
{"RootNode", "Heviest", "Node_1", "Node_2", "Node_3"},
};
This stores all the characters in contiguous memory, that is 3 * 5 * 12 bytes.
Upvotes: 2