我想在 C 中定义不同的字符串数组,然后可以是根据其他一些值选择,即如下所示:
char foo[][10] = {"Snakes", "on", "a", "Plane"};
char bar[][10] = {"Fishes", "in", "a", "Lake"};
char *choice;
if (flag == 1) {
choice = &foo;
} else if (flag == 2) {
choice = &bar;
}
printf("%s%s\n", choice[0] , choice[1]);
flag
为 1 时的预期结果:
蛇
flag
为 2 时的预期结果:
钓鱼
但是上面的代码给出了一个segmentation fault
错误,而我尝试了对char
的不同定义,即char*
和char **
。怎么做才对?在这个问题上是否有很好的教程,即关于指针、数组、上面示例中的 foo
究竟是什么...
最佳答案
如果只使用指针数组会更容易:
int main(void)
{
const char *foo[] = { "Snakes", "on", "a", "Plane" };
const char *bar[] = { "Fishes", "in", "a", "Lake" };
const int flag = 17;
const char **choice = (flag == 1) ? foo : bar;
printf("%s %s\n", choice[0], choice[1]);
return 0;
}
上面的打印
Fishes in
关于c - 如何在C中选择一个字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17273982/