例如,当我们只初始化 3 个成员中的 1 个时,为什么结构的所有元素都初始化为 0

发布于 2024-10-19 06:46:34 字数 185 浏览 4 评论 0原文

例如:

typedef struct student { 

     int rollno;
     float cgpa;
     char name[20];

}Student;

Student me= {0,0}; // will intilize name with all zeros

For Example:

typedef struct student { 

     int rollno;
     float cgpa;
     char name[20];

}Student;

Student me= {0,0}; // will intilize name with all zeros

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

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

发布评论

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

评论(3

小傻瓜 2024-10-26 06:46:34

事情就是这样。这是标准的预期行为。数组也是如此。例如,

int a[3] = {1}; // a is {1, 0, 0}
int a[3];       // a is {undefined, undefined, undefined}    

至于原理是什么,我认为是保持结构完全初始化或根本不初始化......也许:)

That's the way it is. This is the standard expected behavior. The same is with arrays. E.g.

int a[3] = {1}; // a is {1, 0, 0}
int a[3];       // a is {undefined, undefined, undefined}    

As to what was the rationale, I think it was to keep the struct either initialized completely or not at all... maybe :)

蒗幽 2024-10-26 06:46:34

一个常见的误解是 Something x = {0}; 应该将所有成员初始化为相同的值。

C 标准规定,如果“聚合”中的所有元素(数组、结构体等)未显式初始化,则应初始化其余值,就好像它们具有静态存储持续时间一样。

所有具有静态存储持续时间的元素,即用关键字 static 声明的元素和所有全局变量,如果程序员没有显式初始化它们,则必须将它们初始化为零。

因此,在您的示例中,“rollno”和“cgpa”被显式初始化,在这种情况下为零,并且结构的其余部分被初始化,就好像它具有静态存储持续时间一样,这意味着它也将为零。

A common misunderstanding is that Something x = {0}; should initialize all members to the same value.

The C standard states that if all of the elements in an "aggregate" (arrays, structs etc) are not initialized explicitly, then the remaining values should be initialized as if they had static storage duration.

And all elements that have static storage duration, ie those declared with keyword static and all global variables, must be initialized to zero if the programmer didn't initialize them explicitly.

So in your example, "rollno" and "cgpa" are initialized explicitly, to zero in this case, and the rest of the struct is initialized as if it had static storage duration, meaning it will be zero as well.

粉红×色少女 2024-10-26 06:46:34

一旦初始化了结构体的单个字段,整个变量就会进入包含所有其他初始化值的部分。因此所有字段都被初始化,因为该部分在可执行文件中作为字节数组实现。

关于值为 0,我猜想这是因为当变量未初始化时使用 0 有更多机会引发异常。考虑除以零或 NULL 指针异常。

Once you initialized a single field of a struct, the whole variable goes to a section with all other initialized values. So all field are initialized, because that section is implemented in the executable as a byte array.

Regarding the value being 0, I guess that it is because 0 has more chance to raise an exception when a variable is used uninitialized. Think divide by zero or NULL pointer exception.

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