创建一个字符串数组

时间:2014-01-31 23:25:15

标签: c arrays string pointers

我有字符串数组。我想把这些数组放入一个数组中。我怎么能这样做?我试过这个:

char const * const fruits[3] = {
    "apple",
    "banana",
    "orange",
};

char const * const colors[3] = {
    "red",
    "green",
    "blue",
};

char * preset_configurations[3] =
{
    NULL, /* leave the first one blank so that this list is 1-based */
    &fruits,
    &colors,
};

但我得到warning: initialization from incompatible pointer type。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

你需要一个双指针和一些consts(以及摆脱&符号):

char const * const * preset_configurations[3] =
{
    NULL, /* leave the first one blank so that this list is 1-based */
    fruits,
    colors
};

编辑:我想,在我发布上述内容后给出了额外的信息,您问题的最佳解决方案是:

// This will copy the characters of the words into the 3 16-byte arrays.
char fruits[3][16] = {
    "apple",
    "banana",
    "orange"
};
// Ditto.
char colors[3][16] = {
    "red",
    "green",
    "blue"
};
// This is how to point to the above.
char (*preset_configurations[3])[16] = {
    NULL, // this list is 1-based
    fruits,
    colors,
};

这样字符串不再是常量字符串(正如你所说,exec函数不需要)。

答案 1 :(得分:0)

typedef const char const *(*cp3)[3];
cp3 preset_configurations[3] = {
    NULL,
    &fruits,
    &colors,
};
//printf("%s\n", (*preset_configurations[1])[2]);//orange