c, passing struct as argument

2019-07-18 13:34发布

I need to pass some structure as function argument like this

void myFunc(unsigned char c);

I will use myFunc(4), myFunc(8) or so.

Now the function accepts a structure as argument, so I tried

typedef struct {
    unsigned char address;
    unsigned char command;
    unsigned char group;
    unsigned char response;
    unsigned char flags1;
    unsigned char flags2;
}test_t;

void myFunc(test_t test);

myFucn({0,0,0,0,0}); // but this gives me error 

How can I pass const struct as argument without to have to instantiate first ? Just like myFunc(4) as unsigned char.

Thanks

标签: c struct
1条回答
够拽才男人
2楼-- · 2019-07-18 14:10

In C99, you can use a compound literal:

myFunc((test_t) { 0, 0, 0, 0, 0 });

Of course, since the struct is being passed by value, it doesn't matter if you consider it to be "const" or not; whatever the function does to it won't matter to the outside.

In previous versions of C, you cannot do this.

查看更多
登录 后发表回答