简体   繁体   中英

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. The value of x changes to 10 after *(x+1)=10. However the value of *(&y+1) is indeed changed to 10. The statement *(x+1)=10 should not affected x imo.

You used wrong control string for pointer ( %i )

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

You should use %p instead

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM