如何在C中初始化结构

发布于 2025-01-21 21:09:46 字数 259 浏览 2 评论 0原文

我对我如何在C中初始化结构进行了评论,说它不起作用,也不汇编。

这就是我在C中创建和初始化一个结构的方式。

struct {
int a; 
int b;
char arr[3];
.
.
.
} data = {
.a = 1, 
.b = 2
};

main(){
/* do stuff */
}

这是我如何初始化结构并运行和编译的方式。但是我收到评论说这将为C ++编译,但对于C.如果不是,为什么它没有错误地编译?

I got a comment on how I initialize my struct in C, saying that It does not work and it does not compile either.

This is how I create and initialize a structure in C.

struct {
int a; 
int b;
char arr[3];
.
.
.
} data = {
.a = 1, 
.b = 2
};

main(){
/* do stuff */
}

This how I initialize my struct and It works and compiles. Yet I got a comment saying this would compile for c++ but not for C. Can someone ensure me that this correct alternative? If not why is it compiling with no errors?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

心欲静而疯不止 2025-01-28 21:09:46

我认为数据成员arr的声明中有一个错字。而不是

char [3]arr;

您必须编写,

char arr[3];

您可能不会初始化带有空括号的数组。因此,例如,写作

struct {
int a; 
char arr[3];
.
.
.
} data = {
.a = 1, 
.arr = { 0 }
};

实际上足以

struct {
int a; 
char arr[3];
.
.
.
} data = {
.a = 1
};

暗中写入数组,将用零开始初始化。

I think there is a typo in the declaration of the data member arr. Instead of

char [3]arr;

you have to write

char arr[3];

You may not initialize an array with empty braces. So write for example

struct {
int a; 
char arr[3];
.
.
.
} data = {
.a = 1, 
.arr = { 0 }
};

In fact it is enough to write

struct {
int a; 
char arr[3];
.
.
.
} data = {
.a = 1
};

The array implicitly will be initialized with zeroes.

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