c - 为什么 int (*ptr)[10] 类型的指针需要数组的地址而不仅仅是数组本身

标签 c arrays pointers

数组返回指向第一个元素的指针。我有简单的代码如下:

int a[10] = {1,2,3};//Filled three elements
int (*ptr)[10];//pointer to an array of 10 ints
ptr = a;

我低于警告。

warning: assignment from incompatible pointer type

如果我如下所示修改指针定义,则不会出现警告

ptr = &a;

为什么第一次分配会导致警告? &a 是否返回指向 10 个元素的数组的整数指针?请帮助理解。谢谢

最佳答案

Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.

除了 sizeof&alignof 运算符之外,数组会衰减为指针。

int a[10] = {1,2,3};//Filled three elements
int (*ptr)[10];//pointer to an array of 10 ints
ptr = a;

在赋值 ptr = a 中,a 衰减为指向 int (int *) 的指针,该指针指向第一个元素。

int a[10] = {1,2,3};//Filled three elements
int (*ptr)[10];//pointer to an array of 10 ints
ptr = &a;

这里&a的类型是int (*)[10],它是一个指向10个int数组的指针,与ptr类型相同。这是将指针分配给数组的正确方法。

另请注意,a&a 的值本身相同,唯一的区别在于类型。

关于c - 为什么 int (*ptr)[10] 类型的指针需要数组的地址而不仅仅是数组本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51740319/

相关文章:

c - 在C程序中跨套接字实现多线程的问题

java - Java中如何关联数组?

arrays - 在 Swift 中对 UIImage 类型数组进行排序

php - 来自多个上传表单的数组,上传图像然后插入数据库(PHP,MySQL)

c++ - 如何传递 unique_ptr 来设置我的对象的成员变量?

c - 无法在集合程序 (C) 中获取数组

C 预处理器语法

c - 如何让一个子进程等待它的兄弟?

c -++ 指针运算符

c++ - Const 在模板函数参数列表中被忽略