谁能解释这些值将如何打印以及为什么 p 和 *p 返回相同的值。
#include <stdio.h>
int main(){
int arr[] = {1,2,3,4};
int (*p)[4];
p = &arr;
printf("%u %u %u %u %u", arr, &p, p, *p, **p);
p++;
printf("\n%u %u %u %u %u", arr, &p, p, *p, **p);
return 0;
}
我的机器输出如下:
2686768 2686764 2686768 2686768 1
2686768 2686764 2686784 2686784 2686792
最佳答案
你的例子很乱,但指针运算通常很乱,对类型不尊重。从类型理论的角度来看,你的例子没有意义。
arr
指向数组的第一个元素。请注意,arr[i]
等同于 *(arr+i)
。 arr
是 int
类型的 4 元素数组。
p
是指向 int
类型的 4 元素数组的指针。
你把&arr
的地址赋值给p
,它和arr
的地址相同(只是类型不同,见下文) .
然后你打印出来,这意味着:
arr
是数组首元素的地址&p
是p
的地址
p
是&arr
的地址(整个数组),也就是arr
的地址,也就是第一个元素的地址在数组中*p
是arr
的地址,也就是数组第一个元素的地址**p
正在尝试取消引用*p
,这是取消引用arr
,它实际上是数组的第一个元素<
在你递增p++
之后:arr
和&p
不会改变,其余的会改变
来自C Book
We have already emphasized that in most cases, the name of an array is converted into the address of its first element; one notable exception being when it is the operand of sizeof, which is essential if the stuff to do with malloc is to work. Another case is when an array name is the operand of the & address-of operator. Here, it is converted into the address of the whole array. What's the difference? Even if you think that addresses would be in some way ‘the same’, the critical difference is that they have different types. For an array of n elements of type T, then the address of the first element has type ‘pointer to T’; the address of the whole array has type ‘pointer to array of n elements of type T’; clearly very different. Here's an example of it:
int ar[10]; int *ip; int (*ar10i)[10]; /* pointer to array of 10 ints */ ip = ar; /* address of first element */ ip = &ar[0]; /* address of first element */ ar10i = &ar; /* address of whole array */
关于c - 指向数组的指针究竟是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31047644/