c - 部分初始化 C 结构

标签 c struct initialization variable-assignment

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 not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

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

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

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

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

...

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

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

相关文章:

c - 基本 C 编程 : Run-Time Check Failure #3 - The variable 'pro1' is being used without being initialized

jquery - FullCalendar 仅在重新加载时出现

c++ - 如何在可能不存在的目录中创建文件?

c - 排序结构不起作用

C# 编码 C++ 结构继承

c++ - 将不正确的值类型分配给结构属性时出现笑脸!

java - 在for语句的初始化中可以初始化多少个变量?

C函数用破折号格式化字符串

c++ - C/C++ Linux下的Packet Sniffer

c - 如何从 ext2 block 组读取 inode 表?