gpt4 book ai didi

C 指向字符串数组的指针

转载 作者:太空宇宙 更新时间:2023-11-04 01:22:35 25 4
gpt4 key购买 nike

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

“警告:从不兼容的指针类型 [-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]);
}

最佳答案

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

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

Demo.

注意:您不需要在字符串文字和 printf 格式字符串中都有 \n 字符,除非您想要双-间距。

关于C 指向字符串数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38318623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com