如何在C中选择字符串数组?

时间:2013-06-24 11:06:53

标签: 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]); 

flag为1的预期结果:

Snakeson

flag为2的预期结果:

Fishesin

但是上面的代码会出现segmentation fault错误,而我尝试了char的不同定义,即char*char**。怎么做对了?关于这个问题是否有一个很好的教程,即关于指针,数组,foo在上面的例子中是什么......

2 个答案:

答案 0 :(得分:5)

如果你只使用指针数组会更容易:

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

答案 1 :(得分:2)

使用char数组,你需要这个:

char foo[][10] = {"Snakes", "on", "a", "Plane"};
char bar[][10] = {"Fishes", "in", "a", "Lake"};
char (*choice)[10];
if (flag == 1) {
    choice = &foo[0];
} else if (flag == 2) {
    choice = &bar[0];
} 
printf("%s%s\n", choice[0] , choice[1]); 

要让choice[1]引用正确的插槽,它必须是指向数组元素类型的指针,并初始化为&foo[0]而不是&foo。虽然它们是相同的地址,但它们是不同的数据类型。


如果你希望choice是一个指向2-dim char数组的指针,那么就可以完成它,但你在声明指针时指定了两个数组维,并记得取消引用它:

char foo[][10] = {"Snakes", "on", "a", "Plane"};
char bar[][10] = {"Fishes", "in", "a", "Lake"};
char (*choice)[4][10];
if (flag == 1) {
    choice = &foo;
} else if (flag == 2) {
    choice = &bar;
} 
printf("%s%s\n", *choice[0] , *choice[1]);