#include <stdio.h>
int main (){
int x=10,*a=&x;
int *b=(int *)&a;
printf("%d %d %d %d %d %d ",x,a,*a,b,*b,**b);
return 0;
}
In this little program variable x is assigned value 10 and then address of x is assigned to pointer variable a. Now proper way is int **b=&a because b should be a pointer to pointer. But I thought it’s ultimately the address which gets stored. So to store address of a to an int pointer b, I use typecasting int *b=(int *)&a. Now address of a got stored in b. So if I use *b, it give identical result as a.
But when I extend this further to **b it doesn’t give the same result as *a which I expected. In fact it gives an error. *b and a are same so when i ask to retrieve from this value like **b and *a this doesn’t work. For this I assumed a concept that *b and a are same in value but they are different in type. The value given by a is pointer and value given by *b is an integer so **b is not possible like *a.
But I still think that it should work.
I am using Dev C++ 4.9.9.2 which is a 32 bit compiler. The memory allocated to an int and int * is the same, that is 4 bytes. And *b and a have same bit representation also. So when I write *(*b) I used same value as in *(a). But what is the preventing factor? The format is like *(some bit representation) and the bit representation is identical in case of *b and a. So the value of x should be retrieved. Please explain the preventing factor.
*bis an integer, and you’re not allowed to apply the unary*to an integer. (How would the compiler know whether you expected the bit pattern to point to an int, char, short, or whatever?) You can cast the integer back to a pointer and then deference it:*(int*)*b, which should do what you expect.