结构体的初始化如何在函数调用中用作变量。 ANSI-C 版本
我正在编写 C89、C90、Ansi-C 代码。我的函数之一需要一个结构作为参数。我想通过该结构的初始化来调用该函数,而不是先创建一个结构,然后将其传递给该函数。
以下是一些有效的片段。
typedef struct {
char* EventName;
char* Message;
} Event;
Event myEvent = {
.EventName = "infomessage",
.Message = "Testmessage"
};
Notify(myEvent);
这是我想写的,但不起作用:
Notify({.EventName = "infomessage", .Message = "Testmessage"});
或者更好的
Notify({"infomessage", "Testmessage"});
编辑:LabCVI 使用 ISO 9899:1990 标准。
I am writing C89, C90, Ansi-C Code. One of my functions requires a struct as a parameter. I want to call the function with the initialization of that struct rather than creating a struct first then passing it to the function.
Here are some snippets which work.
typedef struct {
char* EventName;
char* Message;
} Event;
Event myEvent = {
.EventName = "infomessage",
.Message = "Testmessage"
};
Notify(myEvent);
and here is what I would like to write but which doesn't work:
Notify({.EventName = "infomessage", .Message = "Testmessage"});
or even better
Notify({"infomessage", "Testmessage"});
EDIT: LabCVI is using the ISO 9899:1990 standard.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用复合文字
(Event){"infomessage", "Testmessage"}
,即Use the compound literal
(Event){"infomessage", "Testmessage"}
, ie我认为你不能,因为这会混合声明和代码。还,
在 C90 中,一种方法是给它一个临时名称,例如:
注意旧的初始化方法
{ data1, data2 }
。如果您担心范围,也可以将其括在大括号中并在顶部进行初始化。
I don't think you can, as that would be mixing declarations and code. Also,
In C90, one way is to just give it a temporary name, like:
Notice the older
{ data1, data2 }
method of initialization.If you are worried about scope, enclosing it in braces with the initialization at the top is also possible.