#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;” 替換為此“ *struct queue *q=(struct queue *)malloc(sizeof(struct queue));” 有效,是什么原因?
uj5u.com熱心網友回復:
發生分段錯誤是因為您沒有為 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);
uj5u.com熱心網友回復:
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 enqueue(struct queue *q, int value) 中撰寫代碼以在每個操作中分配新記憶體 */ /我了解您試圖通過將 size 分配給 10 來一次性確定記憶體,但您不能這樣做。因為您在此處分配的部分只是您放入 arr[0] 的值,您不能使用它作為您的串列的大小。/
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/532236.html
標籤:C数据结构分段故障
上一篇:C在結構內動態存盤字串的位置
