C,传递结构作为参数 [英] c, passing struct as argument
本文介绍了C,传递结构作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要通过一些结构,这样的函数参数
I need to pass some structure as function argument like this
void myFunc(unsigned char c);
我将使用 myFunc的(4)
, myFunc的(8)
左右。
现在函数接受结构参数,所以我试图
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
我如何能够通过常量结构作为无参数,必须先实例化?
就像myFunc的(4)无符号字符。
How can I pass const struct as argument without to have to instantiate first ? Just like myFunc(4) as unsigned char.
感谢
推荐答案
在C99中,您可以使用复合文字:
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.
在的C previous版本中,你不能做到这一点。
In previous versions of C, you cannot do this.
这篇关于C,传递结构作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文