【问题标题】:Printing Structs inside Structs在结构内部打印结构
【发布时间】:2021-07-12 06:20:34
【问题描述】:

我想打印结构的结构。我的代码目前看起来是这样的:(这里我没有粘贴,但是 Shelf 只是一个 struct Shelf 的 typedef)。

struct shelf {
    struct book *books;
    struct shelf *next;
};

struct book {
    int text;
    int image;
    struct book *next;
};

Shelf create_shelf(void) {
    Shelf new_shelf = malloc(sizeof (struct shelf));
    new_shelf->next = NULL;
    new_shelf->books = NULL;
    return new_shelf;
}

我现在想像这样打印我的书架、里面的书以及每本书中的每个图像和文本:

输出: , , ... 等等,其中 text1 和 image1 指的是 book1。

我已经开始尝试编写此代码,但我无法理解下面的打印功能有什么问题。我将如何处理打印所有内容同时只允许输入“货架货架”作为我的函数中的参数?

void print_everything (Shelf shelf) {
    while (shelf != NULL) {
        printf("%d, %d", shelf->books->text, shelf->books->image);
    }
}

谢谢!

【问题讨论】:

  • 使您的print_everything 跟随next 指针,直到它到达列表的末尾。现在,当您传递一个非空参数时,它是一个无限循环。
  • 上面的代码还能运行吗?
  • 你确定文字和图片应该只是数字吗?

标签: c pointers struct printf typedef


【解决方案1】:

考虑到Shelfstruct shelf * 的typedef 而不是struct shelf

  void print_everything (Shelf shelf) {
        while (shelf != NULL) {
            printf("%d, %d", shelf->books->text, shelf->books->image);
            shelf = shelf -> next; // Add this line
        }
    }

【讨论】:

  • 糟糕,sizeof(Shelf) 只是指针的大小。
  • @DavidGrayson 感谢您指出!
  • 格式说明符字符串周围的引号怎么样?
  • 考虑从不在typedef中隐藏指针?
猜你喜欢
  • 1970-01-01
  • 2012-12-12
  • 2021-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-17
  • 2021-06-21
相关资源
最近更新 更多