Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code using pointers not retrieve the value of x using b?

Tags:

c

pointers

#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.

like image 408
melyfony Avatar asked Jul 25 '26 16:07

melyfony


1 Answers

It seems to work fine for me, once your variable declarations are cleaned up a bit:

int main (){
        int x = 10;
        int* a = &x;
        int** b = &a;
        printf("%d  %d  %d  %d  %d  %d  ",x,a,*a,b,*b,**b);
        return 0;
}

I'd suggest that the problem is that you declared b with the wrong type (and then cast &a into that type). It is not an int*, it is an int**, i.e. a pointer to a pointer to an integer. You could of course cast *b to the desired type in your printf() statement, but why not just declare it correctly in the first place?

Here's an ideone example: http://ideone.com/idwfd

like image 199
aroth Avatar answered Jul 28 '26 09:07

aroth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!