我想知道为什么这个函数中的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->next
是NULL,因此在以下行中:
Node* currNode = head;
while (currNode && index > currIndex) {
currNode = currNode->next;
currIndex++;
}
您currNode
指向NULL,后来导致:
if (index > 0 && currNode == NULL) return NULL;