Reputation: 93
Consider the code snippet below:
int *p=NULL,*t=NULL,e;
char l=65;
char *k=&l;
p=(int*)&l;
t=(int*)k;
e=*t;
printf("%d\n",*p);
printf("%d\n",*t);
printf("%d\n",e);
The output of the above snippet is as follows:
16705
16705
65
Now it is evident that &l
is an address to a char and p=(int*)&l
lets an int pointer i.e p point to the same location this is the same with pointer t. Now if I dereference p rightly so it will try to dereference 4 consecutive memory blocks (assuming int points to 4 bytes) and print out a garbage value of sorts which happens for *t
as well but when I print e I get 65 back which is confusing to me as e=*t
which should be same as *p
or *t
perhaps?
Upvotes: 0
Views: 143
Reputation: 44310
Dereferencing p
(i.e. using *p
) is undefined behavior as there isn't an int
at that location. Anything may happen... and no one can explain the output you get.
Compiling your code with "gcc -Wall -Wextra -pedantic ..." gives me:
main.cpp:19:1: warning: array subscript 'int[0]' is partly outside array bounds of 'char[1]' [-Warray-bounds]
19 | printf("%x\n",*p);
which directly tells you that the program has problems that needs to be fixed.
Upvotes: 3