问题
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