gpt4 book ai didi

c - 创建对象排队列表时出现段错误

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

任务是在main中创建对象并将它们传递给其他函数,这将创建一个队列类型的列表。这就是我正在使用的算法:

  • 编写一个 Node * 类型的函数,它将返回指向列表的最后一个Node的指针

  • 要在列表末尾插入Node,需要获取指向最后一个Node的指针

  • 创建一个新的节点
  • 将已传递给函数的对象分配给新创建的Node
  • 使最后一个节点中的下一个指向新节点

代码如下:

typedef struct Node{
int val;
char str[30];
struct Node *next;
}Node;

void printList(const Node * head);
void queue(Node *head, Node *object);
Node *getLast(Node *head);

int main(void){

Node *head = NULL;
Node *object = (Node *)malloc(sizeof(Node));
int c = 0;
while(1){
printf("This int will be stored in Node %d.\n", ++c);
scanf("%d", &object->val);
if(!object->val){
puts("You've decided to stop adding Nodes.");
break;
}
fflush(stdin);
printf("This string will be stored in Node %d.\n", c);
fgets(object->str, 30, stdin);
if(!(strcmp(object->str, "\n\0"))){
puts("You've decided to stop adding Nodes.");
break;
}


queue(head, object);


}
printList(head);

return 0;
}

void printList(const Node *head){
if(head == NULL){
puts("No list exists.");
exit(1);
}
while(1){

printf("|||Int: %d|||String: %s|||\n", head->val, head->str);

if(head->next){
head = head->next;
}
else{
break;
}
}
}

Node *getLast(Node *head){
if(head == NULL){
return NULL;
}
while(head->next){
head = head ->next;
}
return head;
}

void queue(Node *head, Node *object){
Node *last = getLast(head);
Node *tmp = (Node *)malloc(sizeof(Node));
*tmp = *object;
tmp -> next = NULL;
last -> next = tmp;
}

也许问题出在 getLast return NULL 上。但话又说回来,当我创建一个仅由 int 组成的 list 时,同样的事情发生了。

最佳答案

正如评论部分所指出的,last->next = tmp 第一次调用queue() 会失败,因为getLast() 返回NULL。正确的解决方案是这样的:

  void queue(Node **head, Node *object){                                          
Node *last = getLast(*head);
Node *tmp = (Node *)malloc(sizeof(Node));
*tmp = *object;
tmp -> next = NULL;

if (last != NULL)
last -> next = tmp;
else
*head = tmp;
}

并从 main() 调用queue(&head, object)

关于c - 创建对象排队列表时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50888974/

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