c - 为什么指针中包含的内存地址和指针的地址相同?

标签 c pointers

指针变量只是指向内存中的其他变量地址。显然指针变量在内存中有自己的地址。

但是,这段代码为两者提供了相同的内存地址。

int num=10;
int *ptr=#
printf("Address of variable num: %p\n",ptr);
printf("Address of pointer ptr: %d\n",&ptr);

如果同时打印它们,那么它似乎按预期工作。

Address of variable num: 0028FF3C

Address of pointer ptr: 0028FF38


但是如果我一次打印一个,那么它会为两者提供相同的地址。

printf("Address of variable num: %p\n",ptr);
//printf("Address of pointer ptr: %d\n",&ptr);

Address of variable num: 0028FF38

//printf("Address of variable num: %p\n",ptr);
printf("Address of pointer ptr: %d\n",&ptr);

Address of pointer ptr: 0028FF38


我在 Windows 7 机器上使用 mingw 编译器。

最佳答案

编译器只需要保证一个变量在使用期间一直存在。

int a = 5;
int b = 7;
printf( "a * 5 = %d\n", a * 5); /* after this point, a is no longer needed */
printf( "b * 9 = %d\n", b * 9); /* after this point, b is no longer needed */

因此编译器可以将 b 的初始化推迟到 a 完成之后,并且只使用一个内存位置。

同样在这个例子中,它可能将常量 2​​5 和 63 压入堆栈并且不为 a 或 b 创建任何存储空间。

关于c - 为什么指针中包含的内存地址和指针的地址相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33581797/

相关文章:

c - 尝试使用文件 i/o 读写来查找两个文件不同的字节位置

检查字符串是否为回文 - 当我编译程序时关闭

c - 当我在 Unix 中调用 fork() 时会发生什么?

c++ - 如何将 t[i][j] 转换为指针样式引用

C++ 属性声明

CPLEX、C 编码

c - 创建临时目录的可靠方法

C 指针和队列的指针

C++ 结构创建错误没有命名类型

c - 错误不兼容的指针类型?