简体   繁体   中英

Pointer to declared but uninitialized variable in C

I've been reviewing the basics of singly linked list In C with materials from Stanford CS Library , where I came cross the following code:

struct node{
    int              data;
    struct node*     next;
};

struct node* BuildWithDummyNode(){
    struct node dummy;
    struct node* tail = & dummy;    // this line got me confused
    int i;
    dummy.next = NULL;
    for (i=1;i<6;i++){
        Push(&(tail->next), i);    
        tail = tail->next;
    }
    return dummy.next;
}

Probably not revenant, but the code for Push() is:

void Push(struct node** headRef, int data){
    struct node* NewNode = malloc(sizeof(struct node));
    newNode->data = data;

    newNode->next = *headRef;
    *headRef = newNode;
}

Everything runs smoothly, but I've always been under the impression that whenever you define a pointer, it must point to an already defined variable. But here the variable "dummy" is only declared and not initialized. Shouldn't that generate some kind of warning at least?

I know some variables are initialized to 0 by default, and after printing dummy.data it indeed prints 0. So is this an instance of "doable but bad practice", or am I missing something entirely?

Thank you very much!

Variable dummy has already been declared in the following statement:

struct node dummy;

which means that memory has been allocated to it. In other words, this means that it now has an address associated with it. Hence the pointer tail declared in following line:

struct node* tail = & dummy;

to store its address makes perfect sense.

"But here the variable "dummy" is only declared and not initialized."

The variable declaration introduces it into the scope. You are correct in deducing it's value is unspecified, but to take and use its address is well defined from the moment it comes into scope, right up until it goes out of scope.

To put more simply: your program is correct because you don't depend on the variables uninitialized value, but rather on its well defined address.

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.

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