【发布时间】:2021-08-22 21:55:48
【问题描述】:
我刚刚用 C 语言编写了一个函数,它应该在链表的末尾添加一个节点,但是当我编译程序时,控制台中什么也没有。这是函数的主体:
void addAtend(node *head, int val){
node *temp;
node *tempVal;
temp =head;
tempVal= (node*)malloc(sizeof(node));
if(tempVal==NULL){
printf("Error! Memory was not allocated!");
exit(-1);
}
tempVal ->data=val;
tempVal->next=NULL;
while (temp!=NULL)
{
temp = temp->next;
}
temp->next = tempVal;
}
这是完整的 C 程序:
#include <stdlib.h>
#include <stdio.h>
typedef struct linked {
int data;
struct linked *next;
} node;
//function to ietrate through a linked list
void printer(node *head){
node *temp = head;
while (temp!=NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}
//function to add a value to the end of the linked list
void addAtend(node *head, int val){
node *temp;
node *tempVal;
temp =head;
tempVal= (node*)malloc(sizeof(node));
if(tempVal==NULL){
printf("Error! Memory was not allocated!");
exit(-1);
}
tempVal ->data=val;
tempVal->next=NULL;
while (temp!=NULL)
{
temp = temp->next;
}
temp->next = tempVal;
}
int main(){
node *ptr = (node*)malloc(sizeof(node));
if(ptr==NULL){
printf("Error!");
exit(-1);
}
node *head;
head = ptr;
ptr->data = 30;
ptr->next = (node*)malloc(sizeof(node));
ptr->next->data =50;
ptr->next->next = NULL;
addAtend(head, 40);
printer(head);
}
输出如下所示: enter image description here
谁能看看这段代码,告诉我函数有什么问题?
【问题讨论】:
-
while (temp!=NULL)。当该循环结束时temp将是NULL,因此循环后面的行将取消引用 NULL 指针,这(在大多数系统上)会导致段错误。
标签: c data-structures struct linked-list singly-linked-list