【问题标题】:Initializing a struct's members初始化结构的成员
【发布时间】:2016-05-21 17:20:11
【问题描述】:

我正在阅读 C 语言中的 structs,但我并不完全理解 struct 的初始化方式。 请考虑以下代码:

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

struct tnode {
    char *word;
    int count;
    struct tnode *left;
    struct tnode *right;
};


int main (void)
{
    struct tnode *root;
    struct tnode tn1;
    root = &tn1;
    printf("%d\n", root->count);

    if (root->word == NULL)
        printf("word is NULL\n");
    else
        printf("word is not NULL\n");

    if (root->right == NULL)
        printf("rightis NULL\n");
    else
        printf("right is not NULL\n");
}

输出:

0
word is NULL
right is not NULL

我不明白为什么root-&gt;right 没有初始化为NULL。有人可以请教一下吗?

【问题讨论】:

  • 试试static struct tnode *root;看看结果。

标签: c struct initialization


【解决方案1】:

我不明白为什么root-&gt;right 没有初始化为NULL

C 只初始化全局定义和/或声明的变量 static 本身。如果代码没有明确完成,所有其他变量都将保持未初始化状态。

您显示的代码读取未初始化的变量。这样做可能会调用未定义的行为。看到0NULL 只是(坏)运气。变量可以包含任何内容。

来自C11 Standard (draft) 6.7.9/10

如果具有自动存储持续时间的对象未显式初始化,则其值为 不定。如果具有静态或线程存储持续时间的对象未初始化 明确地,那么:

——如果是指针类型,则初始化为空指针;

——如果是算术类型,则初始化为(正或无符号)零;

——如果它是一个聚合,每个成员都根据这些规则(递归地)初始化, 并且任何填充都被初始化为零位;

——如果它是一个联合,第一个命名的成员根据这些被初始化(递归) 规则,并且任何填充都被初始化为零位;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    • 1970-01-01
    • 2020-12-17
    相关资源
    最近更新 更多