gpt4 book ai didi

C : Singly linked list sorting segmentation fault

转载 作者:太空宇宙 更新时间:2023-11-03 23:48:03 25 4
gpt4 key购买 nike

void List_sort (struct nodeStruct **headRef){
struct nodeStruct *tempNode = *headRef;
struct nodeStruct *nextNode, *smallestNode;
while (tempNode != NULL){
nextNode = tempNode->next;
smallestNode = tempNode;
while (nextNode != NULL){
if (nextNode->item < smallestNode->item) {
smallestNode = nextNode->next;
}
nextNode = nextNode->next;
}
int tempInt = tempNode->item;
tempNode->item = smallestNode->item;
smallestNode->item = tempInt;
tempNode = tempNode->next;
}
}

不知道它为什么会产生段错误,应该没有对 NULL 的编辑。段错误。 0x00000000004008d4 in List_sort (headRef=0x7fffffffe458) at list.c:130 130 tempNode->item = smallestNode->item;有人知道为什么要这样做吗?

更新:执行了建议,不再出现段错误,但排序不正确。

Value: 1
Value: 2
Value: 7
Value: 3
Value: 4
Value: 6
Value: 5
Value After Sort: 1
Value After Sort: 2
Value After Sort: 4
Value After Sort: 3
Value After Sort: 5
Value After Sort: 6
Value After Sort: 7

最佳答案

这是不对的:

            if (nextNode->item < smallestNode->item) {
smallestNode = nextNode->next;
}

应该是:

            if (nextNode->item < smallestNode->item) {
smallestNode = nextNode;
}

关于C : Singly linked list sorting segmentation fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28144635/

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