c - 数组上不兼容指针类型警告的分配

标签 c linux pointers gcc

为什么下面的代码会发出警告?

#include <stdio.h>
int main()
{
    int arr[3] = {1,2,3};
    int *ptr, *ptr1;
    ptr = &arr;
    ptr1 = arr;
    printf("ptr is %p\t ptr1 is %p\n",ptr, ptr1);
    ptr++;
    ptr1++;
    printf("ptr is %p\t ptr1 is %p\n",ptr, ptr1);
    return 0;

}
$ gcc test.c -o test
test.c: In function ‘main’:
test.c:6:6: warning: assignment from incompatible pointer type [enabled by default]
  ptr = &arr;

我也尝试更改 ptrint **ptr ,但它仍然失败并出现相同的警告。 arr是一个指针;我将它存储在指针中。这里有什么错误吗?

最佳答案

arr is a pointer

不,不是。

MSVC(令人惊讶地)对此代码给出了更详细的警告:

warning C4047: '=': 'int *' differs in levels of indirection from 'int (*)[3]'

不带下标的语法&array包含长度信息。将分配更改为 &arr[0] 会删除警告并按预期工作。

关于c - 数组上不兼容指针类型警告的分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54310733/

相关文章:

c - sscanf 字符串拆分不起作用

C - 如何添加结构成员?

ruby-on-rails - 运行 webbrick 的 Ubuntu 上的 ImageMagick 冲突

linux - 如何在 RHEL 中安装 java jdk?

linux - 带有 nginx 路由的 linux 上的 asp.net 核心不起作用

c++ - 非拥有指针作为现代 C++ 中的类成员

c - 子进程死亡后,子进程中声明的所有指针都会被释放吗?

C 编译器无意义的错误?

C - 链表的 addLast 函数的奇怪行为

c - 如何更好地从指向某个地址的地址读取值