gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:26:06 24 4
gpt4 key购买 nike

我想知道为什么这个函数中的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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com