首页 > 解决方案 > 为什么数组指针的地址与存储在该指针中的数据相同?

问题描述

如果你尝试那段代码

#include<stdio.h> int main() { 


// Pointer to an integer 
int *p;  

// Pointer to an array of 5 integers 
int (*ptr)[5];  
int arr[] = { 3, 5, 6, 7, 9 };

// Points to 0th element of the arr. 


// Points to the whole array arr. 
ptr = &arr;  

printf("p = %p, address of P = %p\n", p, &p); 
return 0; }

你会得到类似的东西p = 0x7fff8e9b4370, P address = 0x7fff8e9b4340 ,这意味着指针 P 的地址是一个东西,它里面的数据是另一个

但是如果你尝试像这样使用数组的指针

#include<stdio.h> int main() { 


// Pointer to an integer 
int *p;  

// Pointer to an array of 5 integers 
int (*ptr)[5];  
int arr[] = { 3, 5, 6, 7, 9 };

// Points to 0th element of the arr. 
p = arr; 

// Points to the whole array arr. 
ptr = &arr;  

printf("arr  = %p, arr address = %p\n", arr, &arr); 
return 0; } 

你会得到类似的东西arr = 0x7ffda0a04310, arr address = 0x7ffda0a04310

那么为什么指针数据与内存中的指针地址相同?!当我们取消引用 arr 指针的地址时,我们应该得到数字 3 但据我所知,这是0x7ffda0a04310内存中的地址位置0x7ffda0a04310作为数据

所以我在哪里弄错了?

标签: carrayspointers

解决方案


这是因为当您使用数组的符号时,它实际上计算为&arr(地址到第一个元素)。所以正因为如此arr&arr都是同一个地址(但不是同一个类型!)。

arr是类型int*

&arr是类型int(*)[5]

不同之处在于您执行指针算术时。递增arr将转到下一个元素的地址。所以*(arr+1)本质上是一样的arr[1]。递增&arr跳过整个数组(递增指针总是会跳过整个类型的大小)


推荐阅读