I was reading about struct
s in the C language and I do not fully understand the way a struct
is initialized. 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
. Could someone please throw some light?
I can't understand why
root->right
is not initialized toNULL
.
C does only initialise variables defined globally and/or declared static
be itself. 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. The variables could hold anything.
From the C11 Standard (draft) 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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.