Suraj Jain Suraj Jain - 5 months ago 15
C Question

Explain Pointer Dereferencing?

I Am a beginner in c and I want to know what is meant by dereferencing pointer and also if i made a pointer point to a character which is of one byte . Then i print the character value dereferencing pointer then how does the pointer know that it has to read only one byte ?


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.