简体   繁体   English

设置一个指针,其余为NULL

[英]Setting a pointer, remaining NULL

I'm trying to implement a linked list and I have come upon a very stubborn and frustrating problem. 我正在尝试实现一个链表,但遇到了一个非常顽固且令人沮丧的问题。 Here is the relevant code. 这是相关的代码。

Node* current = list->head;
Node* previous = malloc(sizeof(Node*));
previous = NULL;
while(current != NULL){
    if(current == NULL){
        printf("current is null");
    }
    last = current;
    current = current->next;
    if(last == NULL){
        printf("last is null");
    }
} 

Now the problem with it is it is printing 现在的问题是它正在打印

"last is null" “最后为空”

frequently but doesn't print out 经常但不打印出来

"current is null" “当前为空”

once. 一旦。 If current is not null and i set last = current then why does last stay null? 如果current不为null并且我将last设置为current,那么为什么last保持为null?

Thank you for any and all insights 感谢您提供的所有见解

Firstly, you don't want to use sizeof(Node*) which will allocate the size of a pointer (32-bit / 64-bit / something else depending on the platform). 首先,您不想使用sizeof(Node*)来分配指针的大小(32位/ 64位/其他取决于平台)。 It is pointless since you can and already do define a pointer using Node* previous . 这毫无意义,因为您可以并且已经使用Node* previous定义了指针。

Secondly, expression in while() checks if current is not equal to NULL . 其次, while()表达式检查current是否等于NULL If current is equal to NULL it will simply exit the loop so your if(current == NULL) comparison won't execute. 如果current等于NULL ,它将直接退出循环,因此您的if(current == NULL)比较将不会执行。

You can make that comparison valid if you put if(current == NULL) after current = current->next; if(current == NULL)current = current->next;之后放置if(current == NULL) ,则可以使该比较有效current = current->next; . However, if last is null is printed, something else is also completely flawed with your code because current has to be null before last . 但是,如果输出last is null ,则代码中也存在其他缺陷,因为current必须在last之前为null。 It is surprising it is not giving a segmentation fault or something. 令人惊讶的是它没有给出分割错误或其他东西。

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

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