[英]Dereferencing an incremented pointer causing the pointer to change its value?
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *x= 0;
int y = 0;
x = &y;
*x = 1;
printf("%i\n",x);//an address
printf("%i\n",*x);//1
*(x+1)=10;
printf("%i\n",x);//10 ---->unexpected
printf("%i\n",x+1);//14 ---->more wierd
printf("%i\n",*(x+1));//seg fault
return 0;
}
In this case the last printf statement will output a seg fault.在这种情况下,最后一个 printf 语句将输出段错误。 The value of x changes to 10 after *(x+1)=10.
*(x+1)=10 后 x 的值变为 10。 However the value of *(&y+1) is indeed changed to 10. The statement *(x+1)=10 should not affected x imo.
然而*(&y+1) 的值确实改为10。语句*(x+1)=10 不应该影响x imo。
You used wrong control string for pointer ( %i
)您为指针使用了错误的控制字符串 (
%i
)
printf("%i\n",x);//10 ---->unexpected
You should use %p
instead你应该改用
%p
printf("%p\n",(void*) x);
Also the access to pointer (x + 1)
is causes undefined behavior, because the initial pointer x
points to a single integer, and so dereferencing (x + 1)
is out of bound and undefined.此外,访问指针
(x + 1)
会导致未定义行为,因为初始指针x
指向单个整数,因此取消引用(x + 1)
是越界且未定义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.