Aas*_*ahi 1 c pointers memory-address
我尝试使用指针来玩一些指定值'i'和我发现的内容,因为有两个不同的地址分配给声明%u和%lu,%llu.变量如何可能在同一个执行实例中具有两个不同的地址 -
#include <stdio.h>
int main(void)
{
int i;
float f;
printf("\nEnter an integer:\t");
scanf("%d",&i);
printf("\nValue of address of i=%u",&i);
printf("\nvalue of address of i=%d",&i);
printf("\nValue of address of i=%lu",&i);
printf("\nValue of address of i=%llu",&i);
printf("\nvalue of i=%d",i);
printf("\nvalue of i=%u",i);
printf("\nvalue of i=%lu",i);
printf("\nvalue of i=%llu\n",i);
}
Run Code Online (Sandbox Code Playgroud)
这是输出 -
aalpanigrahi@aalpanigrahi-HP-Pavilion-g4-Notebook-PC:~/Desktop/Daily programs/pointers$ ./pointer001
Enter an integer: 12
Value of address of i=1193639268
value of address of i=1193639268
Value of address of i=140725797092708
Value of address of i=140725797092708
value of i=12
value of i=12
value of i=12
value of i=12
Run Code Online (Sandbox Code Playgroud)
在这里我们可以清楚地看到,对于%u和%d,地址是1193639268(尽管%d和%u的输出在所有情况下可能不相等),%lu和%llu的输出是140725797092708,它的物理是什么意义.
用于打印指针的正确格式说明符是%p.
使用了错误的格式说明,如%d,%u,%lu,或%llu调用未定义的行为.
作为您所看到的特定行为,您的特定实现的指针可能是一个8字节的值,而一个int或unsigned int可能是一个4字节的值.因此,使用%d或%u仅读取传入函数的8字节值的前4个字节并打印该值.当您使用%lu或时%llu,所有8个字节都被读取和打印.
同样,因为您正在调用未定义的行为,所以您不能依赖此特定输出来保持一致.例如,在32位模式和64位模式下编译可能会产生不同的结果.最好使用%p,也可以将指针强制转换为void *,因为这是预期的特定指针类型%p.