Ale*_*lex 0 c arrays string pointers
我想在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]);
Run Code Online (Sandbox Code Playgroud)
案例中的预期结果flag是1:
Snakeson
预期结果flag为2:
Fishesin
但上面的代码给出了一个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;
}
Run Code Online (Sandbox Code Playgroud)
以上打印
Fishes in
Run Code Online (Sandbox Code Playgroud)