[英]Keep segfaulting when trying to pass struct into function
我正在嘗試將指向隊列的指針傳遞給createQueue函數:
void createQueue(struct pqueue *queue){
queue = malloc( sizeof(struct pqueue) );
queue->root = malloc(sizeof(struct node));
queue->root->next = 0;
queue->root->taskID = 12;
queue->root->priority = 5000;
}
我還嘗試像這樣添加到新創建的隊列中:
void add(struct pqueue *queue, int taskID, int priority){
struct node *conductor;
conductor = queue->root;
if ( conductor != 0 ) {
while ( conductor->next != 0)
{
conductor = conductor->next;
}
}
conductor->next = malloc( sizeof(struct node) );
conductor = conductor->next;
if ( conductor == 0 )
{
printf( "Out of memory" );
}
/* initialize the new memory */
conductor->next = 0;
conductor->taskID = taskID;
conductor->priority = priority;
}
從主要功能來看:
int main()
{
struct pqueue *queue;
createQueue(queue);
add(queue, 234093, 9332);
}
...但是我一直在斷斷續續。 有什么原因會持續發生嗎?
編輯:
pqueue和node的結構如下:
struct node {
int taskID;
int priority;
struct node *next;
};
struct pqueue{
struct node *root;
};
在C語言中,一切都是通過值傳遞的。 因此,當您調用createQueue(queue)
,您createQueue(queue)
指針的副本傳遞給該函數。 然后,在函數內部,當您說queue = malloc(...)
,您正在設置該指針的副本等於您新分配的內存-保持main()
的指針副本不變。
您想做這樣的事情:
void createQueue(struct pqueue **queue)
{
(*queue) = malloc( ... );
}
int main(void)
{
struct pqueue *queue;
createQueue(&queue);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.