2016-03-12 56 views

回答

1

在C你不能初始化結構成員內聯像你嘗試用nodeQ成員做。

您需要在創建結構來初始化成員。

所以,你需要做的是這樣

struct queue q = { malloc(sizeof(struct tree *)), 0, 0 }; 

struct queue *q = malloc(sizeof(struct queue)); 
q->nodeQ = malloc(sizeof(struct tree *)); 
q->front = 0; 
q->rear = 0; 

注意,我do not cast the result of malloc

0

你所遇到的問題是初始化結構,當你定義它。 當使用struct name_of_struct {...};您正在定義數據類型。由於這個原因,你不能給它一個真正的價值。

struct tree{ 

    int data;   
    struct tree *left,*right;  

};  


struct queue{ 

    struct tree ** nodeQ; 
    int front;  
    int rear;  

};  

這應該做一個定義,還記得使用縮進和評論你的代碼,因爲這將導致更多的理解程序,您實際上會明白從現在開始2周。

而且我覺得其實有一個錯誤在你的代碼,不應該nodeQ是一個正常的指針,而不是一個雙指針?如果您嘗試解除引用(接受指針引用的內容)兩次,則會出現seg錯誤。

這裏是你應該如何初始化nodeQ的內容假定其單指示器和功能,我會在主函數這一次初始化。

#include <stdio.h> 
#include <stdlib.h>  




struct tree{ 

    int data;   
    struct tree *left,*right;  

};  


struct queue{ 

    struct tree * nodeQ; 
    int front;  
    int rear;  

}; 



int main(void) 
{ 
    struct queue my_queue; 
    if(my_queue.nodeQ=malloc(sizeof(struct tree))) 
     fprintf(stderr, "Unable to allocate memory for my_queue nodeQ\n"); 


    return 0; 
} 
相關問題