Suraj Jain Suraj Jain - 1 year ago 66
C Question

Confused pointer Dereferencing?

How does dereferencing Pointer Know how many bytes it has to read ?

If I make a program like

int y = 1234;
char *p = &y;
int *j = &y;
printf("%d " , *p);
printf("%d" , *j);

Output is : -46 1234

I want to know what is happening behind the scenes and how does dereferencing pointer p is giving me

Answer Source

If you have something like ,

int x = 1234 ;
int *p = &x;

If You Dereference Pointer p then it will correctly read integer bytes. Because You declared it to be pointer to int . It will know how many bytes to read by sizeof() operator. Generally size of int is 4 bytes but it is machine dependent that is why it will use sizeof() operator to know correct size and will read so .If you have something like this

 int y = 1234;
 char *p = &y;
 int *j  = &y;

Now pointer p points to y but we have declared it to be pointer to a char so it will only read one byte or whatever byte char is of . 1234 in binary would be represented as 00000000 00000000 00000100 11010010.

Now if your machine is little endian it will store the bytes reversing them 11010010 00000100 00000000 00000000 . 11010010 is at address 0 Hypothetical address , 00000100 is at address 1 and so on.

So now if you dereference pointer p it will read only first byte and output will be -46 as byte read would be 11010010(Because we pointed signed char ,so the most-significant bit is the sign bit. First bit 1 denotes the sign. 11010010 = –128 + 64 + 16 + 2 = –46.) and if you dereference pointer j it will completely read all bytes of int as we declared it to be pointer to int . And output will be 1234

And Also if you declare pointer j as int *j then *j will read sizeof(int) usually 4 bytes and *(j+1) will also read that many bytes . Same goes with char or any other data type the pointer pointed to them will read as many bytes there size is of. Generally char is of 1 byte.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download