[英]How do I set a structure member from its pointer in c
If I pass a struct type to a function using its address, how do I set the members in the struct? 如果使用结构的地址将结构类型传递给函数,如何在结构中设置成员?
#include <stdlib.h>
#include <stdio.h>
typedef struct foo {int avalue} foo_t;
void setmember(foo_t *foo_item){
foo_item.avalue = 42;
}
int main(void) {
foo_t dafoo;
setmember(&dafoo);
printf("%d\n", dafoo.avalue);
return 0;
}
If I try this as is, I get the following error. 如果按原样尝试,则会出现以下错误。
error: request for member 'avalue' in something not a structure or a union 错误:请求成员“ avalue”的形式不是结构或联合
I understand the error, I don't know the fix. 我了解错误,但不知道解决方法。 I've tried de-referencing with: 我尝试使用以下方法取消引用:
*foo_item.avalue = 42;
Your attempt is almost correct. 您的尝试几乎是正确的。 .avalue
binds tighter than *
, though, so you need parens: .avalue
绑定比*
更紧密,因此您需要括号:
(*foo_item).avalue = 42;
This operation is so common that C provides the ->
shorthand syntax for it: 此操作非常普遍,C为它提供了->
速记语法:
foo_item->avalue = 42; // same thing
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.