c program pointer -
i trying programs in c face problem program can 1 tell me problem , want know when in above case if pointer value incremented on write previous value address
#include<stdio.h> int main() { int a=9,*x; float b=3.6,*y; char c='a',*z; printf("the value %d\n",a); printf("the value %f\n",b); printf("the value %c\n",c); x=&a; y=&b; z=&c; printf("%u\n",a); printf("%u\n",b); printf("%u\n",c); x++; y++; z++; printf("%u\n",a); printf("%u\n",b); printf("%u\n",c); return 0; }
suppose value got in above program (without increment in pointer value )is 65524 65520 65519 , after increment value of pointer 65526(as 2 increment int ) 65524(as 4 increment float ) 65520(as 1 increment char variable )
then if in case new pointer address overwrite content of previous address , value contained @ new address
first of all, assume calls printf
supposed display values of x
, y
, z
, or addresses of a
, b
, , c
, correct? in case need change them to:
printf("%p\n", x); printf("%p\n", y); printf("%p\n", z);
these take account size of pointer on processor, if different size of int
. print address in hexadecimal, more common since addresses can quite large.
and after increment value of pointer 65526(as 2 increment int )
assuming you're on platform int
2 bytes (on modern home pcs int
4 now).
then if in case new pointer address overwrite content of previous address , value contained @ new address ......plz help
you haven't dereferenced of pointers here. memory occupied a
, b
, , c
still untouched; you've done changed x
, y
, , z
pointing to. if dereference 1 of pointers after incrementing it, modifying memory past variable pointed to. if a
@ address 65526 decimal , int
2 bytes:
int *x = &a; // x points integer @ "65526" (a) x++; // x points integer @ "65528", still @ 65526 *x = 5; // you've modified memory @ addresses 65528 , 65529.
if 65528 or 65529 contained other important data (like b
or c
) you've corrupted program's state.
Comments
Post a Comment