Quite a few things are working together to give the result $64$
- The value $320=0\text{x}0140$ is in binary $101000000 = 00000001$ $01000000$
- Your computer is more likely to be using little endian than big endian.
- The platforms that considered big endian are: AIX, HP-UX, IBM mainframe, Macintosh, and Solaris.
- The platforms that considered little endian are: AXP/VMS, Digital UNIX, Intel ABI, OS/2, VAX/VMS, and Windows.
- So if address pointed by $\&i$ is $2000$,
- the byte at $2000$ is $01000000$,
- the byte at $2001$ is $00000001$
- If your system assigns more than $2$ bytes for type $int$ , the bytes from $2002$ onwards would be zero.
- Now at line 5, $\&i$ gives address pointer for address 2000. It is type casted into character pointer by use of (char *) type casting and char *ptr is initialized with this value.
- At line 6, *ptr gives binary value $(01000000)$ of 1 byte long character pointed by pointer ptr. The use %d in printf causes implicit type conversion of that value $(01000000)$. hence it is shown as integer value $64$.
The same results can be obtained using :
#include <stdio.h>
int main()
{
int i=320;
int *ptr=&i;
printf("%d",*(char *)ptr);
return 0;
}
or
#include <stdio.h>
int main()
{
int i=320;
int *ptr=&i;
printf("%d",(char)*ptr);
return 0;
}