开发者

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

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 开发者_如何学Pythonyou refer to the value *p points to from **p?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜