初始化结构的成员

时间:2016-05-21 17:20:11

标签: c struct initialization

我正在阅读C语言中的struct,我并不完全理解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->right未初始化为NULL。有人可以请一些光吗?

1 个答案:

答案 0 :(得分:8)

  

我无法理解为什么root->right未初始化为NULL

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

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

来自C11 Standard (draft) 6.7.9/10

  

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

     

- 如果它有指针类型,则将其初始化为空指针;

     

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

     

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

     

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

相关问题