gpt4 book ai didi

c - 为什么这个程序在这个队列程序中给出段错误

转载 作者:行者123 更新时间:2023-11-30 14:59:11 26 4
gpt4 key购买 nike

这是队列的C程序。我刚刚为插入值编写了它。我遇到的问题是每当插入第一个元素时都会出现段错误。

#include <stdio.h>
#include <malloc.h>
struct node{
int data;
struct node *next;
};

struct queue {
struct node *front;
struct node *rear;
};

struct queue *q;

void create_queue(struct queue *);
struct queue *insert(struct queue *,int);

int main()
{

int val, option;
create_queue(q);

do
{

printf("\n *****MAIN MENU*****");
printf("\n 1. INSERT");
printf("\n Enter your option : ");
scanf("%d", &option);

switch(option)
{
case 1:
printf("\n Enter the number to insert in the queue:");
scanf("%d", &val);
q = insert(q,val);
break;

}

}while(option != 5);

return 0;
}

void create_queue(struct queue *q)
{
q = (struct queue *)malloc(sizeof(struct queue));
q->rear = NULL;//how this happened without any error??
q->front = NULL;
}

struct queue *insert(struct queue *q,int val)
{

struct node *ptr;

ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("error in allocating\n");
return -1;
}
ptr->data = val;
if(q->front == NULL)
{
q->front = ptr;//here I get segmentation fault
q->rear = ptr;
q->front->next = q->rear->next = NULL;
}
else
{
q->rear->next = ptr;
q->rear = ptr;
q->rear->next = NULL;
}

return q;
}

我的程序出了什么问题?为什么分配新节点不起作用,当前语法是什么?

最佳答案

这里的问题是,当您使用全局变量调用函数并在函数参数中接受该变量时,该函数参数将成为被调用函数的本地参数。

这样,局部变量会隐藏全局变量,并且由于 C 使用按值传递来传递函数参数,因此对本地副本所做的任何更改都不会反射(reflect)给调用者。

最后,全局指针p保持未初始化状态。尝试取消引用导致 undefined behavior .

你要么

  • 不需要将全局作为参数传递
  • 传递指针的地址并在函数内部对其进行操作。

也就是说,please see this discussion on why not to cast the return value of malloc() and family in C. .

关于c - 为什么这个程序在这个队列程序中给出段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42985340/

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