Why is the data type needed in pointer declarations?
Data type of a pointer is needed in two situations:
- Dereferencing the pointer
- Pointer arithmetic
How it is used in dereferencing the pointer?
Consider the following example:
{
char *k; //poniter of type char
short j=256;
k=&j; // Obviously You have to ignore the warnings
printf("%d",*k)
}
Now because k is of type char
so it will only read one byte. Now binary value of 256
is 0000000100000000
but because k is of type char
so it will read only the first byte hence the output will be 0.
Note: if we assign j=127 then the output will be 127 because 127 will be held by the first byte.
Now come to pointer arithmetic:
Consider the following example:
{
short *ptr;
short k=0;
ptr=&k;
k++;
ptr++;// pointer arithmetic
}
Are statements k++
and ptr++
are same thing? No, k++
means k=k+1
and ptr++
means ptr=ptr+2
. Because the compiler "knows" this is a pointer and that it points to a short, it adds 2 to ptr instead of 1, so the pointer "points to" the next integer.
For more info refer second chapter of this tutorial.
The data type is needed when dereferencing the pointer so it knows how much data it should read. For example dereferencing a char
pointer should read the next byte from the address it is pointing to while an int
pointer should read 2 bytes.