Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - how do you access value from a pointer to a pointer to that value?

Tags:

c

pointers

This function needs to be passed a pointer to a pointer.

void get_name(person** p) {
    puts(p->name); // this is probably wrong
}

This is how I call the function (I'm not sure about this either):

int main() {
    ...

    get_name(&person); // is this wrong?

    ...
    return 0;
}

Person is obviously a struct with a name property which is a string.

How do you refer to the value *p points to from **p?

like image 579
Gal Avatar asked Dec 17 '10 22:12

Gal


1 Answers

x->y is just a shortcut for (*x).y. * performs indirection (that is, it gives you the thing pointed to by the pointer), so you need to perform indirection twice to get the thing pointed to the pointer that is pointed to by the pointer:

(**p).name
(*p)->name

If person is the name of a typedefed struct, then get_name(&person) is not correct; you need an instance of that struct and you need a pointer to that instance that you can pass to the function:

int main() {
    person p;
    person* pp = &p;
    get_name(&pp);
}

However, it's not exactly clear why get_name needs to take a person**; presumably a person* would be sufficient.

like image 148
James McNellis Avatar answered Sep 30 '22 00:09

James McNellis