How to declare and init two dimensional array of strings?

半世苍凉 提交于 2019-12-11 19:27:15

问题


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?


回答1:


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".




回答2:


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.



来源:https://stackoverflow.com/questions/16836595/how-to-declare-and-init-two-dimensional-array-of-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!