[英]A queue using structs and dynamic memory allocation
我的任務是在C中創建一個隊列數據結構,作為鏈表。 我們的講師為我們提供了大量代碼來實現堆棧,但是我們必須調整它來創建一個隊列。 我們的講師給我們的代碼最終沒有編譯和segfaulting與我為隊列編寫的代碼完全相同。 我對結構,malloc和C一般都是新手,所以我可能會忽略一些令人痛苦的事情。
這是我正在使用的代碼:
#include <stdio.h>
#include <stdlib.h>
struct node{
int data; //contains the actual data
struct node *prev; //pointer to previous node (Closer to front)
struct node *next; //pointer to next node (Closer to back)
};
typedef struct node *Nodepointer;
struct queue{
Nodepointer front;
Nodepointer back;
};
typedef struct queue *Queuepointer;
main(){
Queuepointer myqueue; //create a queue called myqueue
init(myqueue); //initialise the queue
Nodepointer new = (Nodepointer)malloc(sizeof(struct node));
myqueue->front = new;
}
int init(Queuepointer q){
q = (Queuepointer)malloc(sizeof(struct queue));
q->front = NULL;
q->back = NULL;
}
我們的想法是隊列結構'包含'隊列中的第一個和最后一個節點,並且在創建節點時,會更新myqueue。 但是,我甚至無法達到那個部分(pop和push是為了簡潔起見而省略的)。 代碼是行中的segfaulting
myqueue->front = new;
使用以下gdb輸出:
Program received signal SIGSEGV, Segmentation fault.
0x08048401 in main () at queue.c:27
27 myqueue->front = new;
知道我做錯了什么嗎?
當你調用init時:
int init(Queuepointer q){
q = (Queuepointer)malloc(sizeof(struct queue));
q->front = NULL;
q->back = NULL;
}
您將指向隊列的指針傳遞給函數,並初始化該指針在函數內指向(在內存中)的位置。 通過設置q = ...
,您將為q = ...
分配新值。
不幸的是,調用函數沒有看到這一點。 您需要將指針傳遞給指針:
int init(Queuepointer * qp){
Queuepointer q = (Queuepointer)malloc(sizeof(struct queue));
q->front = NULL;
q->back = NULL;
// Set qp:
*qp = q;
}
然后更改調用函數:
init(&myqueue);
的init(myQueue中); 通過值傳遞指向未分配內存的指針。 因此,init不做任何事情(相反,在隨機位置寫隨機事物)。
然后,myqueue-> stuff再次做到了。
你應該使用指針指針。
Init將接收隊列**,並被稱為init(&myqueue)。 在里面,* myqueue =()malloc的東西
另外,我建議您使用這些typedef。 他們的風格相當糟糕。
我看到的第一個問題是“init”函數將分配的指針寫入“q”,這不是你原來的“myqueue”。 請記住,C按值傳遞其參數。 可能的糾正(不完美,只是暗示)是
Queuepointer init(void)
Queuepointer q;
q = (Queuepointer)malloc(sizeof(struct queue));
q->front = NULL;
q->back = NULL;
return q;
}
`
並在“主要”:
myqueue = init();
還要注意,在程序中,您不會初始化malloc分配的元素。 malloc通常不會清理它分配的內存。
問候
你是按值傳遞myqueue所以在init()發生的分配是myqueue的副本而不是myqueue。
所以正確的版本是:
int init(Queuepointer* q){
*q = (Queuepointer)malloc(sizeof(struct queue));
*q->front = NULL;
*q->back = NULL;
}
你可以從main調用init()
init(&myqueue);
int init(Queuepointer q){
q = (Queuepointer)malloc(sizeof(struct queue));
q->front = NULL;
q->back = NULL;
}
輕微的挑剔,但你的init函數沒有返回值,所以可能將其更改為:
void init(Queuepointer *q) {
要么
int init(Queuepointer * qp){
Queuepointer q = (Queuepointer)malloc(sizeof(struct queue));
q->front = NULL;
q->back = NULL;
*qp = q;
if(q) {
return 1;
} else return 0;
}
根據您想要執行錯誤檢查的方式進行調整。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.