简体   繁体   中英

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

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:

(*foo_item).avalue = 42;

This operation is so common that C provides the -> shorthand syntax for it:

foo_item->avalue = 42;  // same thing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM