我有一个结构与其内的另一个结构数组,我无法初始化结构。如何在结构中初始化一个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