例如,当我们只初始化 3 个成员中的 1 个时,为什么结构的所有元素都初始化为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
事情就是这样。这是标准的预期行为。数组也是如此。例如,
至于原理是什么,我认为是保持结构完全初始化或根本不初始化......也许:)
That's the way it is. This is the standard expected behavior. The same is with arrays. E.g.
As to what was the rationale, I think it was to keep the struct either initialized completely or not at all... maybe :)
一个常见的误解是
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.
一旦初始化了结构体的单个字段,整个变量就会进入包含所有其他初始化值的部分。因此所有字段都被初始化,因为该部分在可执行文件中作为字节数组实现。
关于值为 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.