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

标签 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";

并让它发挥作用。该代码给了我错误“请求非结构或 union 中的成员‘段落’”。

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

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

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

我想,这应该不难弄清楚,但我有点被困在这里。

最佳答案

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

关于c - 将结构数组作为结构的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20107693/

相关文章:

c - 打开并解析文件

c - 在 C 中将数组作为参数传递

c++ - 很好地初始化结构的 union

php - 使用 SLIM3 将 PHP 数组转换为 JSON 数组并获取响应

javascript - 在索引处连接两个 javascript 数组

c - 是否可以将具有延迟函数的结构数组声明为某些元素

c - 段错误(Core Dumped)--结构和指针--C语言

c - int=float%int; 有什么问题?

c - 了解由于原型(prototype)不匹配而导致的意外结果 (C89)

c - Cortex-M7 的 DS-5 配置