c - 为什么局部函数中的变量不会消失? (链表的插入函数)

标签 c linked-list

我想知道为什么这个函数中的newNode没有消失?

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

typedef struct node {
    float hs;
    float sm;
    struct node *next;  
}Node;

Node* InsertNode(Node* head, int index, float hs, float sm){
    if(index < 0) return NULL;

    int currIndex = 1;
    Node* currNode = head;
    while (currNode && index > currIndex) {
        currNode = currNode->next;
        currIndex++;
    }

    if (index > 0 && currNode == NULL) return NULL;

    Node* newNode = (Node*) malloc(sizeof(Node));
    newNode->hs = hs;
    newNode->sm = sm;

    if(index == 0){
        newNode->next = head;
        head = newNode;
    }

    else {
        newNode->next = currNode->next;
        currNode->next = newNode;
    }

    return head;
}

void Display(Node* head) {
    Node* currNode = head;
    while(currNode != NULL){
        printf("(%.2f, %.2f ) ", currNode->hs, currNode->sm);
        currNode = currNode->next;
    }
}

int main(){
    Node* poly1 = NULL;
    Node* poly2 = NULL;
    poly1 = InsertNode(poly1, 0, 5, 4);
    poly1 = InsertNode(poly1, 1, 6, 3);
    poly1 = InsertNode(poly1, 2, 7, 0);
    Display(poly1);
    getch();
    return 0;
}

我尝试编写一个用于插入元素的函数。我知道局部变量在被调用函数结束后会消失,但它仍然有效? 请帮我解决这个问题。

最佳答案

当你调用 -> poly1 = InsertNode(poly1, 1, 6, 3); 时,poly1 已经是 head 并且 head->nextNULL,因此在这些行中:

Node* currNode = head;
while (currNode && index > currIndex) {
    currNode = currNode->next;
    currIndex++;
}

您正在使 currNode 指向 NULL,稍后结果为:

if (index > 0 && currNode == NULL) return NULL;

关于c - 为什么局部函数中的变量不会消失? (链表的插入函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57933682/

相关文章:

c - 为什么这段代码总是产生相同的结果?

c - 左值需要错误混淆吗?

c - 为什么gnu make命令默认编译同名的c文件

c - 为什么在我的代码运行后进程被终止?处理返回 255

java - Java 中自定义链表的节点中的多种不同数据类型

java - 如何使 LinkedList 从另一个类可访问到主类?

c++ - 为什么这个二进制转换不起作用?

c - 我需要做什么才能链接到 xlib?

关于链接列表中节点的混淆

c - 添加到链接列表的末尾不起作用