C指向字符串数组的指针

时间:2016-07-12 01:25:27

标签: c arrays string pointers

如何解决字符串设置值的矩阵问题。我想用指针。以下是警告:

“警告:从不兼容的指针类型初始化[-Wincompatible-pointer-types]”

char *country[]={"USA\n","UK\n","Chaina\n","Singapore\n","Scotland\n"};
for (int i =0; i <5; i++) {
     printf("\n CHECK val=%s\n",country[i]);    
}
char *(*cp)[5]=&country[2];
for (int i =0; i <3; i++) {
    printf("\n POINTER  val=%s\n",(*cp)[i]);
}

1 个答案:

答案 0 :(得分:4)

您收到警告,因为&country[2]没有返回指向五个C字符串数组的指针。但是,您不需要这样的指针,因为简单的char **指针将允许您创建数组中间的别名:

char **cp = &country[2];
for (int i = 0; i < 3 ; i++) {
    printf("\n POINTER  val=%s\n", cp[i]);
}

Demo.

注意:除非您想要双倍间距,否则字符串文字和\n格式字符串中不需要printf个字符。