while declaring a variable, we need to declare its data type, which tells the compiler to reserve the number of bytes in the memory accordingly. But in case of pointers, we know that their size is always of 2 bytes (in Turbo Compiler) always irrespective of the data type of the variable it is pointing.
If the pointers always take 2 bytes, then what is the need of mentioning the data type while declaring them?
Answer:
Data type of a pointer is needed in two situations:
- Deferencing the pointer
- Pointer arithmetic
How it is used in dereferencing the pointer?
Consider the following example:
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
Note: if we assign j=127 then output will be 127 because 127 will be hold by first byte.
Now come to pointer arithmetic:
Consider the following example:
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 first byte hence the output will be 0. Note: if we assign j=127 then output will be 127 because 127 will be hold by 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 an short, it adds 2 to ptr instead of 1, so the pointer "points to" the next integer.
0 Comments