c - 如何从 c 中的指针设置结构成员

标签 c pointers 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;
}

如果我按原样尝试,我会收到以下错误。

错误:请求成员“avalue”不是结构或 union

我知道错误,但不知道如何解决。我试过取消引用:

*foo_item.avalue = 42;

最佳答案

您的尝试几乎是正确的。不过,.avalue* 绑定(bind)得更紧密,因此您需要括号:

(*foo_item).avalue = 42;

这个操作很常见,C 为它提供了 -> 简写语法:

foo_item->avalue = 42;  // same thing

关于c - 如何从 c 中的指针设置结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32671811/

相关文章:

ios - 创建 CGPoints 的 c 数组

c - C中Valgrind的解读

C:Turbo C 编译器中 for 循环的异常行为

c 指向结构数组的指针

C++返回类型指针声明

在 C 中为未知(大小)结构创建缓冲区

c - ANSI C 中的字符串处理

c - 你应该释放传递给 prctl() 的内存吗?

c - 对三重指针的作用极度困惑

c++ - sem_t union/struct C++ 继承