#include<stdio.h>;
void main(){
int x=10;
int *y=&x+1;
*y=15;
printf("\n Address of x is %u",&x);
printf("\n Value of y is %d",*y);
}
Run Code Online (Sandbox Code Playgroud)
在这段代码中为什么值*y不是15,在输出中x = 25908的值和y = 25912的值?我想知道为什么当我将x的下一个地址的值设为15时,15不会显示为输出?
在你的代码中,通过写作
int *y=&x+1;
Run Code Online (Sandbox Code Playgroud)
您正在访问未分配给您的进程(程序)的内存.它调用未定义的行为.
如果x是数组名称,并且为偏移量(此处为值1)分配了足够的内存,则y从此操作获取的解除引用将是合法的.但是,在这里,x作为单个变量,你不能指望访问所谓的下一个地址,它是无效的.
也就是说,要打印地址,请始终使用表单
printf("Address is %p\n", (void *)&var);
Run Code Online (Sandbox Code Playgroud)
或类似的.