gpt4 book ai didi

c - 添加到单链表末尾 段错误 C

转载 作者:行者123 更新时间:2023-11-30 17:15:46 25 4
gpt4 key购买 nike

我正在尝试创建一个 C 应用程序,在单个链接列表的末尾添加元素,但在读取最后一个元素后出现段错误。

我使用函数 addAtEndSLL() 在末尾添加一个元素。

//Program to add elements at the end of a single linked list
#include <stdio.h>
#include <stdlib.h>

//Basic declaration of a SLL
struct singleList{
int data;
struct singleList *next;
};

//Add an element at the end of a SLL
int addAtEndSLL(struct singleList **startPtr, int value){
struct singleList *newNode;
newNode = (struct singleList *)malloc(sizeof(struct singleList));
if(newNode == NULL){
printf("\nFailed to Allocate Memory");
return;
}

newNode->data = value;
newNode->next = NULL;
if(*startPtr == NULL){
*startPtr = newNode;
} else {
struct singleList *temp = NULL;
temp = *startPtr;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = newNode;
}
}

int main() {
int i, value;
struct singleList *first = NULL, *tempS = NULL;
tempS = first;
for(i = 1; i <= 5; i++){
printf("\nEnter the data:");
scanf("%d", &value);
addAtEndSLL(&first, value);
}

/*****This is where I belive the segfault occurs*****/

while(tempS->next != NULL){
printf("%d", tempS->data);
tempS = tempS->next;
}
return 0;
}

任何帮助将不胜感激。

最佳答案

首先,修复警告:将函数设为 void 而不是 int,并删除最后一个 return(现在不再需要它了)。

接下来,看看代码中的真正问题:当您在 addAtEndSLL 函数中设置 start 时,first 的值保持不变,因为C按值传递参数;其中包括指针。

要解决此问题,请更改函数以接受指向指针的指针(即双星号),向其传递 &first 而不是 first,并添加额外的级别对 addAtEndSLL 内参数的取消引用:

void addAtEndSLL(struct singleList **startPtr, int value) {
...
// Change all uses of start with *startPtr, like this:
if(*startPtr == NULL){
*startPtr = newNode;
}
...
}

关于c - 添加到单链表末尾 段错误 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29876817/

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