取消引用如何处理指向数组的指针? [英] How does de-referencing work for pointer to an array?
问题描述
取消引用时指向元素数组的指针返回一个地址.因为它保存着数组第一个元素的地址,解引用它应该返回一个值.
Pointer to array of elements when dereferenced return an address. Since it is holding the address of the first element of the array, dereferencing it should return a value.
int arr[] = { 3, 5, 6, 7, 9 };
int *p = arr;
int (*ptr)[5] = &arr;
printf("p = %p, ptr = %p\n", p, ptr);
printf("*p = %d, *ptr = %p\n", *p, *ptr);
输出:
p = 0x7fff6ea72d10,ptr = 0x7fff6ea72d10
p = 0x7fff6ea72d10, ptr = 0x7fff6ea72d10
*p = 3,*ptr = 0x7fff6ea72d10
*p = 3, *ptr = 0x7fff6ea72d10
为什么 *ptr 返回数组的基地址,不应该返回那个地址的值吗??
Why does *ptr return the base address of the array, shouldn't it return the value at that address??
推荐答案
为什么 *ptr 返回数组的基地址,不应该吗返回那个地址的值??
Why does *ptr return the base address of the array, shouldn't it return the value at that address??
(p3) 除非它是 sizeof
运算符、_Alignof
运算符或一元 '&'
运算符的操作数,或者是用于初始化数组的字符串文字,类型为类型数组"的表达式被转换为类型为指向类型的指针的表达式" 指向数组对象的初始元素并且不是左值.C11 标准 - 6.3.2.1 其他操作数 - 左值、数组和函数指示符(p3)
(p3) Except when it is the operand of the sizeof
operator, the _Alignof
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. C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3)
int (*ptr)[5] = &arr;
ptr
是int [5]
的数组指针.当您取消引用 ptr
时,您会得到 array of int[5]
.如何访问 int[5]
数组?
ptr
is a pointer-to-array of int [5]
. When you dereference ptr
you get array of int[5]
. How is an array of int[5]
accessed?
规则 6.3.2.1
提供了答案:
"array of type" 被转换为类型为 "pointer to type" 的表达式,它指向数组对象的初始元素...
"array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object...
现在,如果您再次取消引用(例如 **ptr
),那么您将获得第一个元素的值.
Now if you dereference again (e.g. **ptr
), then you get the value of the 1st element.
这篇关于取消引用如何处理指向数组的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!