【问题标题】:C,GCC warning: initialization from incompatible pointer type [duplicate]C,GCC警告:从不兼容的指针类型初始化[重复]
【发布时间】:2020-11-21 01:04:48
【问题描述】:
char strings[10][100], ** ptr = strings;

有人可以帮忙吗?这部分代码有什么问题,**strings == strings[0][0] 和 strings[0][0] 是不是 char?对不起,我的英语真的很糟糕。

【问题讨论】:

  • 嗯,是的,char (*)[100] 不等于 char **。所以char strings[10][100], (*ptr)[100] = strings;
  • 提示:char *a[n]char a[n][m] 之间存在巨大差异。一个是指针数组,另一个是数组数组。一个二维数组被分配为一个连续的块,但是一个指向其他数组的指针数组通常是not

标签: arrays c pointers initialization


【解决方案1】:

编译器识别出strings 是一个数组数组,因此建议相应地声明指针:

char strings[10][100], (*ptr)[100] = strings;

更新:

正如 David C. Rankin 所述,转换发生在 ptr 的初始化中。 strings100 个字符的数组数组 转换为 指向 100 个字符数组的指针,该指针指向该数组数组的第一个元素。此处指定转换:C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3)

【讨论】:

  • 这将有助于解释数组转换为指针并引用C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3)作为转换源。
  • 你是对的。谢谢你的链接,我相应地更新了我的答案。
  • 但是如果我使用这个声明,我就不能使用我的这部分代码:(fgets(*(ptr + ct),99,stdin); //ct of int type. 我怎么能填写所有有这样声明的数组的行?
  • 你可以,fgets (ptr[ct], 100, stdin) 很好。注意,fgets() 不减去 1,fgets (ptr[ct], 100, stdin) 是正确的。在哪里0 <= ct < 10
  • 但在这种情况下我得到错误:无效使用未指定边界的数组。如果我会做 char (* ptr)[100] = strings; 我可以修复它而是 char (* ptr)[] = 字符串;但是,如果我不知道数组的大小(我在函数中使用它),我应该怎么做。
【解决方案2】:

警告:

Warning: initialization of ‘char **’ from incompatible pointer type ‘char (*)[100]’ [-Wincompatible-pointer-types]
    8 |   char strings[10][100], ** ptr = strings;

它说:ptr 和字符串是不同的类型,所以 ptr[0][0¿ & string[0][0] 是不同的

【讨论】:

  • 但是字符串是数组,数组名是第一个元素上的指针。在我的情况下 string = =&string[0]; string[0] == &string[0][0] HENCE string == &&string[0][0] HENCE **string == string[0][0] HENCE 字符串类型是 char **。它有什么问题?
  • 为了测试你的代码我使用:int main(int argc, string argv[]) { char strings[10][100], **ptr = strings; printf("%s\n", strings); if (strings[0][0] == ptr[0][0]) printf("Same"); else printf("Not the same"); return 0; } 这里:它打印不一样但是如果我更改为`char strings[10][100], (*ptr)[100] = strings; 它返回相同,因为有相同的类型
猜你喜欢
  • 1970-01-01
  • 2011-09-01
  • 2013-12-16
  • 1970-01-01
  • 2021-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多