简体   繁体   English

指向C中已声明但未初始化的变量的指针

[英]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: 我一直在审查C中单链表的基础知识和来自斯坦福CS图书馆的资料 ,我在这里找到了以下代码:

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: 可能不是rev​​enant,但Push()的代码是:

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. 但是这里变量“dummy”只是声明而不是初始化。 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? 我知道一些变量默认初始化为0,并且在打印dummy.data之后它确实打印了0.所以这是“可行但不好的练习”的实例,还是我完全错过了什么?

Thank you very much! 非常感谢你!

Variable dummy has already been declared in the following statement: 变量dummy已在以下语句中声明:

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: 因此指针tail在以下行中声明:

struct node* tail = & dummy;

to store its address makes perfect sense. 存储它的地址非常有意义。

"But here the variable "dummy" is only declared and not initialized." “但是这里变量”dummy“只是声明而不是初始化。”

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. 更简单地说:你的程序是正确的,因为你不依赖于未初始化的变量值,而是取决于它定义良好的地址。

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

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