我正在尝试制作一个在单个链表的末尾添加元素的ac应用程序,但是在读取最后一个元素后出现了分段错误。
我使用函数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
,并删除last return
,现在不再需要。
接下来,是代码中的真正问题:在函数start
内部进行设置时,由于C按值传递参数addAtEndSLL
,因此值first
保持不变。包括指针。
要解决此问题,请将函数更改为接受指向指针的指针(即双星号),&first
而不是传递first
给它,然后对里面的参数添加额外级别的取消引用addAtEndSLL
:
void addAtEndSLL(struct singleList **startPtr, int value) {
...
// Change all uses of start with *startPtr, like this:
if(*startPtr == NULL){
*startPtr = newNode;
}
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句