#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(结构队列));“它起作用了,原因是什么?
2条答案
按热度按时间gwbalxhn1#
发生分段错误是因为您没有为q分配内存。
您所写的内容为:
这是一个指标,也就是储存另一个变数之内存位址的变数。您已经建立了可以指向内存的项目,但是没有提供任何内存给它指向。
malloc从堆中为您提供内存,这是分配内存的典型方式,也是注解代码工作的原因。
另一种方法是使用堆栈上的内存:
然后将其用作:
7z5jn7bk2#
/* 但这将只分配内存中的第一部分(仅适用于arr[0])/ / 以便可以在void入队中编写代码(struct queue q,int value)在每个操作中分配一个新的内存 / / 我知道您试图通过将size赋值为10来一次性确定内存,但是你不能这样做。因为你在这里分配的部分只是你放在arr[0]中的一个值,你不能用它作为你的列表的大小。/