指针变量只是指向内存中的其他变量地址。显然指针变量在内存中有自己的地址。
但是,这段代码为两者提供了相同的内存地址。
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 完成之后,并且只使用一个内存位置。
同样在这个例子中,它可能将常量 25 和 63 压入堆栈并且不为 a 或 b 创建任何存储空间。
关于c - 为什么指针中包含的内存地址和指针的地址相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33581797/