gpt4 book ai didi

c - 来自 gdb 调试器的 "Program received signal SIGSEGV, Segmentation fault."错误消息

转载 作者:太空狗 更新时间:2023-10-29 15:31:06 25 4
gpt4 key购买 nike

while 循环中的某些东西给我这个错误。我不知道要查找什么,因为这个错误似乎是找出如何处理我的特定示例的常见方式

#include <stdlib.h>
#include <stdio.h>
/*Structure declarations*/
struct Data {
int id_number;
float ratings;
};
typedef struct Node{
struct Data player;
struct Node *next;
}Node;

/*function declaration*/
void push(struct Node *list_head, int unique_id, float grade);
int main(){
/* Initialize list_head to Null since list is empty at first */
Node *list_head = NULL;
Node *traversalPtr;

push(list_head, 1, 4.0);
push(list_head, 2, 3.87);
push(list_head, 3, 3.60);

traversalPtr = list_head;
while(traversalPtr -> next != NULL){
printf("%d\n",traversalPtr -> player.id_number);
traversalPtr = traversalPtr -> next;
}
}

...function declarations

最佳答案

问题是函数

void push(struct Node *list_head, int unique_id, float grade);

处理 main 中定义的原始指针的副本,因为指针是按值传递的。

你应该像这样声明函数

void push(struct Node **list_head, int unique_id, float grade);

并称它为

push( &list_head, 1, 4.0 );

这是一个如何定义函数的示例(我假设函数将节点附加到它的尾部)。

int push(struct Node **list_head, int unique_id, float grade)
{
struct Node *node = malloc( sizeof( struct Node ) );
int success = node != NULL;

if ( success )
{
node->player.id_number = unique_id;
node->player.ratings = grade;
node->next = NULL;

while ( *list_head ) list_head = &( *list_head )->next;

*list_head = node;
}

return success;
}

也是这个循环

traversalPtr = list_head;
while(traversalPtr -> next != NULL){
printf("%d\n",traversalPtr -> player.id_number);
traversalPtr = traversalPtr -> next;
}

不正确。它应该看起来像

traversalPtr = list_head;
while(traversalPtr != NULL){
printf("%d\n",traversalPtr -> player.id_number);
traversalPtr = traversalPtr -> next;
}

关于c - 来自 gdb 调试器的 "Program received signal SIGSEGV, Segmentation fault."错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58170241/

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