17

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;
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user43975
  • 173
  • 1
  • 2
  • 6

4 Answers4

32

Try

(*foo)->member = 1;

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

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • A doubt example: if the changeMember() funtion is created in a class library and I need to access this in my console app ,how it should be done?? : @Jonathan Leffler – TechBrkTru Jun 04 '15 at 07:34
  • @TechBrkTru: Given that this is C, I'm not sure what you mean by a 'class library'. However, if you mean 'library', then you simply make sure you've got a header with the necessary function declarations in use in the code that needs to call `changeMember()`, and you link the executable with the library that contains the function. That's all completely routine. If you mean something else, you should probably ask your own new question so you can explain properly. – Jonathan Leffler Jun 04 '15 at 07:38
  • @JaredPar Why would we need a pointer to structure pointer to be able to change the member of the structure (is not a pointer enough to do that ?) – Bionix1441 Mar 01 '17 at 15:32
10

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

(*foo)->member = 1;
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
2

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;
}
Zhichao
  • 599
  • 5
  • 14
1

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

mepcotterell
  • 2,670
  • 2
  • 21
  • 28