简体   繁体   English

初始化struct的成员

[英]Initializing a struct's members

I was reading about struct s in the C language and I do not fully understand the way a struct is initialized. 我正在阅读C语言中的struct ,我并不完全理解struct初始化的方式。 Please consider the below code: 请考虑以下代码:

#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");
}

Output: 输出:

0
word is NULL
right is not NULL

I can't understand why root->right is not initialized to NULL . 我无法理解为什么root->right没有初始化为NULL Could someone please throw some light? 有人可以请一些光吗?

I can't understand why root->right is not initialized to NULL . 我无法理解为什么root->right没有初始化为NULL

C does only initialise variables defined globally and/or declared static be itself. C只会初始化全局定义的变量和/或声明为static变量本身。 All other variables are left uninitialised if not done explicitly by the code. 如果代码没有明确地完成,则所有其他变量都保持未初始化。

The code you show reads uninitialised variables. 您显示的代码读取未初始化的变量。 Doing so might invoke undefined behaviour. 这样做可能会调用未定义的行为。 Seeing 0 or NULL is just (bad) luck. 看到0NULL只是(坏)运气。 The variables could hold anything. 变量可以容纳任何东西。

From the C11 Standard (draft) 6.7.9/10 : C11标准(草案)6.7.9 / 10

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. 如果未显式初始化具有自动存储持续时间的对象,则其值不确定。 If an object that has static or thread 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, and any padding is initialized to zero bits; - 如果它是一个聚合,则根据这些规则初始化(递归)每个成员,并将任何填充初始化为零比特;

— if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits; - 如果它是一个联合,则根据这些规则初始化(递归)第一个命名成员,并将任何填充初始化为零位;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM