简体   繁体   English

如何在C中从其指针设置结构成员

[英]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.

相关问题 如何在C中的结构内访问指针成员? - How do I access a pointer member inside a structure in C? 如何使用 C 中的指针访问结构成员? - How do I access a structure member with a pointer in C? 在C中:如何设置指向作为数组的结构成员的指针? - In C: How to set a pointer to a structure member that is an array? 如何从文件中读取大量数据到 C 中的结构或结构数组的指针 - How can I read a large set of data from a file into either a pointer to a structure or array of a structure in C 在C中,指向结构的指针总是指向其第一个成员吗? - In C, does a pointer to a structure always point to its first member? 如何从一个结构指针复制数据到另一个结构成员 - how to do a copy of data from one structure pointer to another structure member 如果void指针是一个结构成员,如何打印它的值 - How to print value of void pointer if its a structure member 我可以在 C 中将结构作为其自身结构的成员吗? - Can I have a Structure as member of its own structure in C? 我如何获得JNA结构数组的C指针 - How do I get c pointer for JNA structure array 如何通过函数的指针从函数设置GtkLabel的文本? - How do I set the text of a GtkLabel from a function via its pointer?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM