C语言 为什么这段代码不起作用?代码应该打印元素,但它只是运行,然后退出,而不显示元素

siv3szwd  于 2022-12-03  发布在  其他
关注(0)|答案(2)|浏览(147)
#include <stdio.h>
#include <stdlib.h>
struct queue
{
    int front;
    int rear;
    int size;
    int *arr;
};

void enqueue(struct queue *q, int value)
{
    if(q->rear!=q->size-1)
    {
        printf("Entry\n");

        q->rear++;
        q->arr[q->rear] = value;
    }
}

int main()
{
    struct queue *q;   /*struct queue *q=(struct queue *)malloc(sizeof(struct queue));*/
    q->front = -1;
    q->rear = -1;
    q->size = 10;
    q->arr = (int *)malloc((q->size) * sizeof(int));

    enqueue(q,14);
    enqueue(q,7);
    enqueue(q,5);
    enqueue(q,4);
    enqueue(q,3);
    enqueue(q,2);
   
    for(int i=0;i<q->rear;i++){
        printf("%d ",q->arr[i]);
    }
    return 0;
}

我期望队列的元素被打印出来。当行“struct queue q;“被替换为“ 结构队列 *q=(结构队列 *)malloc(sizeof(结构队列));“它起作用了,原因是什么?

gwbalxhn

gwbalxhn1#

发生分段错误是因为您没有为q分配内存。
您所写的内容为:

struct queue *q;

这是一个指标,也就是储存另一个变数之内存位址的变数。您已经建立了可以指向内存的项目,但是没有提供任何内存给它指向。
malloc从堆中为您提供内存,这是分配内存的典型方式,也是注解代码工作的原因。
另一种方法是使用堆栈上的内存:

struct queue q;
q.front = -1;
q.rear = -1;
q.size = 10;
q.arr = (int *)malloc((q.size) * sizeof(int));

然后将其用作:

enqueue(&q,14);
7z5jn7bk

7z5jn7bk2#

struct queue *q;
q = (struct queue *)malloc(sizeof(struct queue));  /*In order to write data, you first need to allocated to memory for it. and if you do it like q->arr you will allocated to memory for the second step so (think of this list as an array if you do q->arr you will allocated for arr[1] instead of arr[0])*/ 
q->front = -1;
q->rear = -1;
q->size = 10;

/* 但这将只分配内存中的第一部分(仅适用于arr[0])/ / 以便可以在void入队中编写代码(struct queue q,int value)在每个操作中分配一个新的内存 / / 我知道您试图通过将size赋值为10来一次性确定内存,但是你不能这样做。因为你在这里分配的部分只是你放在arr[0]中的一个值,你不能用它作为你的列表的大小。/

相关问题