“变量应该总是被初始化”是一个经验法则。这不是一个很好的规则,有时(比如你的例子),它必须被违反,至少是暂时的。未初始化的数据(垃圾)本身不会导致问题。
一些程序员会像这样虔诚地初始化他们的变量。
int i = 0;
Node * foo = NULL;
没有什么能强迫你这样做。只是程序员在做不必要的事情。
在解除引用之前初始化指向有意义的指针很重要。
#include <stdio.h>
#include <stdlib.h>
typedef struct LL
{
int value;
struct LL* next;
}Node;
int main (int argc, char ** argv)
{
Node * A; // OK. A points at garbage.
Node * B; // OK. B points at garbage.
B = A; // Dumb, but OK. B now points at the same garbage as A.
B = A->next; // ERROR. You can't dereference garbage.
A = malloc (sizeof(Node)); // A is no longer points at garbage. The newly created A->value and A->Next are garbage though.
B = A->next; // Dumb, but OK. B now points at the same garbage as A->Next.
B->value = 200; // ERROR. B is garbage, you can't dereference garbage.
A->value = 100; // OK. A->value was garbage, but is now 100.
// *********************************
// Enough academic examples. Let's finish making the linked list.
A->next = malloc(sizeof(Node)); // OK. A->value no longer points at garbage.
B = A->next; // OK. B now points at the second node in the list.
B->value = 200; // OK. B->value was garbage, is now 200.
B->next = NULL; // OK. B->Next was garbage, is now NULL.
printf("A: %#x, value: %d, next: %#x\n", A, A->value, A->next);
printf("B: %#x, value: %d, next: %#x\n", B, B->value, B->next);
return 0;
}