【发布时间】:2018-11-25 18:31:57
【问题描述】:
我在将空值分配给指向结构成员的指针(这也是指向结构的指针)时遇到问题。下面的代码正确地将headNode->right 变量设置为null,而不是headNode->left 变量。
typedef struct node {
char *key;
int frequency;
struct node *left;
struct node *right;
struct node *parent;
} node;
void addKey(char key[]) {
extern node *headNode;
node *newNode;
if (headNode != NULL) {
printf("Head node is initialized\n");
if (headNode->left != NULL) printf(" Left is not null\n");
if (headNode->right != NULL) printf(" Right is not null\n");
}
newNode = malloc(sizeof(node*));
newNode->key = malloc(sizeof(char) * (strlen(key) + 1));
newNode->left = malloc(sizeof(node*));
newNode->right = malloc(sizeof(node*));
newNode->parent = malloc(sizeof(node*));
newNode->left = newNode->right = NULL;
newNode->frequency = 1;
newNode->right = NULL;
strcpy(newNode->key, key);
// If this is the first node, assign it as the root
if (headNode == NULL) {
newNode->parent = NULL;
headNode = newNode;
return;
}
}
但是,如果我在 return 语句之前添加以下两行,它可以正常工作。
if (headNode->left == NULL) printf("L is null\n");
else printf("L is NOT null\n");
我不明白 if 语句如何产生影响。在我的代码中,没有其他地方可以分配或更改此变量的值。
【问题讨论】:
-
如果我在最后一个 return 语句之前添加以下两行 – 只有一个
return语句位于if中,它建立了headNode == NULL!? -
我尽量避免使用这种语法:
newNode->left = newNode->right = NULL,因为评估顺序会有所不同,而且会让人困惑。还有为什么要在两行之后设置newNode->right = NULL?
标签: c