Reputation: 674
I was dabbling with c pointers and couldn't explain the following code:
int main()
{
int i = -3;
int *ptr;
int **ptr2;
int ***ptr3;
ptr = &i;
ptr2 = &ptr;
ptr3 = &ptr2;
printf("ptr = %p\n",(void *)ptr);
printf("&ptr = %p\n",(void *)&ptr);
printAddr(&ptr);
printAddr2(&ptr2);
printAddr3(&ptr3);
return 0;
}
void printAddr(int **num)
{
printf("address of int ** = %p\n", (void *)&num);
}
void printAddr2(int ***num)
{
printf("address of int *** = %p\n", (void *)&num);
}
void printAddr3(int ****num)
{
printf("address of int **** = %p\n", (void *)&num);
}
The output is as follows:
ptr = 0xbf9d64a0
&ptr = 0xbf9d64a4
address of int ** = 0xbf9d6490
address of int *** = 0xbf9d6490
address of int **** = 0xbf9d6490
My doubt is why should address (address(int)) == address(address(address(int)))
?
Thanks a lot for the clarification.
I found that this question is relevant:
But the author is explicitly assigning them to be equal.
Upvotes: 4
Views: 202
Reputation: 183968
void printAddr(int **num)
{
printf("address of int ** = %p\n",(void *)&num);
}
That prints out the address of the copy of the passed-in value that the function received. These will likely be all allocated in the same place on the stack, since all these functions take only one argument, and no allocations occur between the calls.
If you want to see the addresses of the pointers in main
, you should either print them directly in main
or have a function
void printAddress(void* p) {
printf("%p\n", p);
}
and call that with
printAddress(&ptr3);
etc.
Upvotes: 5