我有一個結構與其內的另一個結構數組,我無法初始化結構。如何在結構中初始化一個struct數組?
typedef struct stack * Stack;
typedef struct book * Book;
struct book {
char *title;
int pages;
};
struct stack {
int num_books;
Book array[50]
};
我所試圖做的是零本書籍創建一個空的堆棧,但我一直在我什麼都試過讓段故障。
這裏是我的初始化函數:
Stack create_stack(void) {
Stack s = malloc(sizeof(struct stack) * 50);
s->num_books = 0;
// s->array[0]->title = Null;
// s->array[0]->pages = 0;
// the above 2 lines give a seg fault: 11
// I also tried:
// s->array = s->array = malloc(sizeof(struct book) * 50);
// Which gives the error that array type 'Book [50]' is not assignable
return s;
}
如何創建零本書籍空棧?
你需要將malloc作爲'sizeof(struct stack)'的malloc。 50本書的「數組」(它們是typedef的指針)作爲'stack'結構的一部分。 – Hypino
永遠不要使用typedef指針。它只會造成混亂。特別是,看起來像50本書的數組實際上只是50個指針的數組。所以你需要爲這些指針分配內存,然後才能使用它們。 – user3386109
您今天已經問過類似的問題了!你應該遵循你在第一個問題中得到的建議,並在繼續之前先修復缺陷/錯誤!並且在你的代碼中''struct''中沒有'struct'數組! – Olaf