Reputation: 109
I am learning C pointers and quite confused. I tried to search online but couldn't find any clear explanation. This is what I am trying to understand:
int x = 8;
int *ptr = &x;
int **dptr = ptr;
What does **dptr
point to, x
or *ptr
? When I tried to print the content of dptr
I found that it contains the address of x
instead of *ptr
but I am not sure why?
Edited
int x = 8;
int *p = &x;
int **ptr = &p;
int **dptr = ptr;
Upvotes: 0
Views: 167
Reputation: 123448
Given the declarations
int x = 8;
int *p = &x;
int **ptr = &p;
int **dptr = ptr;
Then the following are true:
**dptr == **ptr == *p == x == 8 (int)
*dptr == *ptr == p == &x (int *)
dptr == ptr == &p (int **)
Upvotes: 0
Reputation: 7006
int x = 8;
int *p = &x;
int **ptr = &p;
int **dptr = ptr;
First, the value 8 is stored in x
.
Next, with the statement
int *p = &x;
p
will point to x
( that is , p
now stores the address of x
)
Next
int **ptr = &p;
Now ptr
will store the address of p
, which in turn stores the address of x
int **dptr = ptr;
dptr
stores the address of ptr
which in turn stores the address of p
which points to x
.
So, Now, **dptr
will have the value of the integer x
.
Upvotes: 0
Reputation: 145829
First off, I assume you meant: int **dptr = &ptr;
as int **dptr = ptr;
is invalid.
int x = 8;
int *ptr = &x;
int **dptr = &ptr;
dptr
points to ptr
object.
*dptr
points to x
object.
**dptr
is not a pointer but the int
object x
.
EDIT: question was edited, ptr
was an int *
but seems to be an int **
now...
Upvotes: 2