c, passing struct as argument

风流意气都作罢 提交于 2020-01-05 02:55:18

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/13823886/c-passing-struct-as-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!