简体   繁体   中英

Printing Structs inside Structs

I want to print a structure of structures. My code currently looks like this: (I haven't pasted it here, but Shelf is just a typedef of struct shelf).

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;
}

I now want to print my shelves, the books inside them and each image and text in each of these books like this:

Output: , , ... and so on, where text1 and image1 refers to book1.

I've started to try to code this, but I cannot understand what is wrong with my print function below. How would I approach printing everything while only allowing the input "Shelf shelf" as the argument in my function?

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

Thanks!

Considering Shelf is typedef of struct shelf * and 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
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM