0

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;
2
  • 3
    This shouldn't compile. You can't assign ptr to dptr. One is an int* and one is an int**. Commented May 2, 2015 at 18:09
  • you are right, I meant **ptr. Commented May 2, 2015 at 18:12

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Sorry, I meant int **ptr = &x and int **dptr = ptr.
@Programm-ist in that case it is invalid C. Did you mean int **dptr = (int **) ptr?
what about this then? int x = 8, int *p = &x, int **ptr = &p, int **dptr = ptr;
@Programm-ist then dptr has then the same value as ptr so **dptr is the same as **ptr.
0
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.

Comments

0

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 **)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.