【发布时间】:2012-11-07 03:51:12
【问题描述】:
所以我正在翻阅我的 C 编程教科书,我看到了这段代码。
#include <stdio.h>
int j, k;
int *ptr;
int main(void)
{
j = 1;
k = 2;
ptr = &k;
printf("\n");
printf("j has the value %d and is stored at %p\n", j, (void *)&j);
printf("k has the value %d and is stored at %p\n", k, (void *)&k);
printf("ptr has the value %p and is stored at %p\n", (void *)ptr, (void *)&ptr);
printf("The value of the integer pointed to by ptr is %d\n", *ptr);
return 0;
}
我运行它,输出是:
j 的值为 1,存储在 0x4030e0
k 的值为 2,存储在 0x403100ptr 的值为 0x403100,存储在 0x4030f0
ptr指向的整数的值为2
我的问题是,如果我没有通过编译器运行它,你怎么能通过查看这段代码知道这些变量的地址?我只是不确定如何获取变量的实际地址。谢谢!
【问题讨论】:
-
变量在内存中的布局方式在某种程度上是操作系统的决定。与此相反,数组是顺序的。但是,实际地址永远无法保证。
-
另外,如果你多次执行同一个程序,几乎可以保证每次执行都会得到不同的地址。对于正常变量,您会得到相同的结果,这将是一个极端的巧合。
标签: c pointers memory-address