gpt4 book ai didi

c - 部分初始化 C 结构

转载 作者:太空狗 更新时间:2023-10-29 16:23:33 24 4
gpt4 key购买 nike

link声明“当自动数组或结构具有部分初始值设定项时,余数被初始化为 0”。我决定尝试一下我阅读的内容并编写了以下代码:

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

int main(void)
{
//int arr[3] = {2}; // line no. 7

struct s {
int si;
int sj;
};

struct s myStruct;
myStruct.si = 9;
printf("%d\n", myStruct.sj);
}

我不明白为什么在我注释掉 行号时打印 4096(我认为这是一些“垃圾”值)。 7 当我取消注释 行号时,我得到 0。 7。我认为 arr 声明与 main() 的激活记录(或者更确切地说是 myStruct)无关,它应该看起来像像(假设我们有 line no. 7 未注释):

---------------
| Saved PC |
---------------
| arr[2] |
---------------
| arr[1] |
---------------
| arr[0] |
---------------
| si |
---------------
| sj |
---------------

有人可以解释一下我在这里缺少什么吗?

最佳答案

当你这样做时:

struct s myStruct;
myStruct.si = 9;

您没有初始化 myStruct。您声明它没有初始化程序,然后运行一条语句来设置一个字段。

由于变量未初始化,其内容未定义,读取为undefined behavior .这意味着看似无关的更改可以修改此行为。在您的示例中,添加一个额外的变量发生 导致myStruct.sj 为0,但不能保证会是这种情况。

初始化一个变量,您必须在定义时给它一个值:

struct s myStuct = { 9 };

执行此操作后,您将看到 myStruct.sj 的内容设置为 0。这是根据 the C standard 的第 6.7.8 节保证的。 (突出显示特定于此案例):

10 If an object that has automatic storage duration is notinitialized explicitly, its value is indeterminate. If an objectthat has static storage duration is not initializedexplicitly, then:

—if it has pointer type, it is initialized to a nullpointer;

if it has arithmetic type, it is initialized to (positive orunsigned) zero;

if it is an aggregate, every member is initialized(recursively) according to these rules;

—if it is a union, the firstnamed member is initialized (recursively) according to these rules.

...

21 If there are fewer initializers in a brace-enclosed list than thereare elements or members of an aggregate, or fewer characters in astring literal used to initialize an array of known size than thereare elements in the array, the remainder of the aggregateshall be initialized implicitly the same as objects that have staticstorage duration.

关于c - 部分初始化 C 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37548287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com