How to work with pointer to pointer to structure in C?

这一生的挚爱 提交于 2019-11-26 22:48:52

问题


I want to change member of structure under double pointer. Do you know how?

Example code

typedef struct {
    int member;
} Ttype;

void changeMember(Ttype **foo) {
   //I don`t know how to do it
   //maybe
   *foo->member = 1;
}

回答1:


Try

(*foo)->member = 1;

You need to explicitly use the * first. Otherwise it's an attempt to dereference member.




回答2:


Due to operator precedence, you need to put parentheses around this:

(*foo)->member = 1;



回答3:


You can use a temp variable to improve readability. For example:

Ttype *temp = *foo;
temp->member = 1;

If you have control of this and allowed to use C++, the better way is to use reference. For example:

void changeMember(Ttype *&foo) {
   foo->member = 1;
}



回答4:


maybe (*foo)->member = 1 (if it's dynamically allocated)



来源:https://stackoverflow.com/questions/346730/how-to-work-with-pointer-to-pointer-to-structure-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!