c - 为什么数组指针的地址与存储在该指针中的数据相同?
问题描述
如果你尝试那段代码
#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
作为数据
所以我在哪里弄错了?
解决方案
这是因为当您使用数组的符号时,它实际上计算为&arr
(地址到第一个元素)。所以正因为如此arr
和&arr
都是同一个地址(但不是同一个类型!)。
arr
是类型int*
&arr
是类型int(*)[5]
不同之处在于您执行指针算术时。递增arr
将转到下一个元素的地址。所以*(arr+1)
本质上是一样的arr[1]
。递增&arr
跳过整个数组(递增指针总是会跳过整个类型的大小)
推荐阅读
- php - 通过其他 smtp 服务器从应用程序发送邮件 25
- c - 如何制作 EGLStream Hello World?
- java - 找不到能够从类型转换的转换器
- testrigor - 如何让 TestRigor 在页面加载时在浏览器提示中输入密码
- vue.js - 从父组件导航到子组件时,父 Create() 调用了两次
- javascript - 如何在交易视图中使用线条而不是条形
- android - 这种类型的实现怎么称呼?RecyclerView,布局
- javascript - 下次尝试后显示不透明度的脚本不起作用
- web-scraping - 如何以定义的术语分解字符向量?
- c - switch语句c语言的问题