将结构数组作为结构的成员

时间:2013-11-20 21:46:17

标签: c arrays struct

假设我有以下结构声明:

struct paragraph
{
    char** line;
    int numLines;
}

struct chapter
{
    struct paragraph** paragraph;
    int numParagraphs;
}

struct book
{
    struct chapter** chapter;
    int numChapters;
}

我希望能够做到(并理解)是我可以这样说的:

struct book myBook;

myBook.chapter[0].paragraph[0].line[0] = "This is the first line";

让它发挥作用。该代码给出了错误“请求成员'段落',而不是结构或联合”。

我可以将最后一行更改为:

myBook.chapter[0]->paragraph[0]->line[0] = "This is the first line";

它没有错误(包括编译语句中的-Wall),但它给了我一个分段错误。

我想,这不应该太难以理解,但我有点被困在这里。

2 个答案:

答案 0 :(得分:0)

你的指针都没有为它们分配内存,因此,元素0不存在并导致分段错误。

答案 1 :(得分:0)

struct chapter** chapter;

要声明简单数组,只需使用一个'*'即可。之后你可以通过索引获取数组的任何项目,你的第一行“myBook.chapter [0] .para ...”将编译:

struct chapter* chapter;

无论如何,程序将无法工作,因为您必须为使用malloc / calloc或类似函数声明的所有数组分配内存。否则会出现分段错误错误。

相关问题