结构体的初始化如何在函数调用中用作变量。 ANSI-C 版本

发布于 2024-10-10 04:53:43 字数 535 浏览 10 评论 0原文

我正在编写 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

依 靠 2024-10-17 04:53:43

使用复合文字 (Event){"infomessage", "Testmessage"},即

Notify((Event){"infomessage", "Testmessage"});

Use the compound literal (Event){"infomessage", "Testmessage"}, ie

Notify((Event){"infomessage", "Testmessage"});
记忆で 2024-10-17 04:53:43

我认为你不能,因为这会混合声明和代码。还,

警告:复合文字是 C99 特定的功能 [-Wc99-extensions]

在 C90 中,一种方法是给它一个临时名称,例如:

#include <stdlib.h>
#include <stdio.h>

struct Event { char *EventName, *Message; };

static void Notify(const struct Event e)
    { printf("%s: %s\n", e.EventName, e.Message); }

int main(void) {
    struct Event myEvent = { "infomessage", "Testmessage" };
    Notify(myEvent);
    return EXIT_SUCCESS;
}

注意旧的初始化方法 { data1, data2 }

如果您担心范围,也可以将其括在大括号中并在顶部进行初始化。

I don't think you can, as that would be mixing declarations and code. Also,

warning: compound literals are a C99-specific feature [-Wc99-extensions]

In C90, one way is to just give it a temporary name, like:

#include <stdlib.h>
#include <stdio.h>

struct Event { char *EventName, *Message; };

static void Notify(const struct Event e)
    { printf("%s: %s\n", e.EventName, e.Message); }

int main(void) {
    struct Event myEvent = { "infomessage", "Testmessage" };
    Notify(myEvent);
    return EXIT_SUCCESS;
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文