首页 > 解决方案 > 在结构内部打印结构

问题描述

我想打印结构的结构。我的代码目前看起来是这样的:(我没有在这里粘贴,但是 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);
    }
}

谢谢!

标签: cpointersstructprintftypedef

解决方案


考虑Shelf的是 typedefstruct shelf *和 not 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
        }
    }

推荐阅读