取消引用递增的指针会导致指针更改其值?

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;
}

在这种情况下,最后的 printf 语句将输出段错误。 *(x+1)=10 后 x 的值变为 10。但是 *(&y+1) 的值确实更改为 10。语句 *(x+1)=10 不应该影响 x imo。

您使用了错误的指针控制字符串(%i)

printf("%i\n",x);//10 ---->unexpected

您应该改用 %p

printf("%p\n",(void*) x);

对指针 (x + 1) 的访问也会导致未定义的行为,因为初始指针 x 指向单个整数,因此取消引用 (x + 1) 是越界和未定义的。