首页 > 解决方案 > 如何打印结构的元素?

问题描述

我制作了这个程序来保存关于一本书的信息,但它不能正确打印

#include <stdio.h>

enum Color {red, green, blue};

struct Book{
    int pages;
    char* author;
    char* title;
    enum Color color;
};

void getInfo(struct Book book){
    book.pages= 200;
    book.author = "Cervantes";
    book.title= "El Quijote";
    book.color = green;

}

void showInfo(struct Book book){

    printf("pages: %d\n", book.pages);
    printf("author: %s\n", book.author);
    printf("title: %s\n", book.title);

    switch (book.color) {
        case red:
            printf("Color: red\n");
            break;
        case green:
            printf("Color: green\n");
            break;
        case blue:
            printf("Color: blue\n");
            break;
    }
}

int main(){
    struct Book book1;

    getInfo(book1);
    showInfo(book1);

    return 0;
}

原则上,程序应该很好地保存它们,因为如果我将打印放在保存数据的函数中,它们确实可以正确打印。但是通过模块化程序,它就停止了。

标签: cdata-structures

解决方案


C 是按值传递的,因此对参数所做的任何更改都是函数本地的。如果要更改调用者中的值,则需要传递一个地址。例如:

#include <stdio.h>

enum Color {red, green, blue};
char *colornames[] = { "red", "green", "blue" };

struct Book {
    int pages;
    char *author;
    char *title;
    enum Color color;
};

void
getInfo(struct Book *book)
{
    book->pages= 200;
    book->author = "Cervantes";
    book->title= "El Quijote";
    book->color = green;
};

void
showInfo(const struct Book *book)
{
    printf("pages: %d\n", book->pages);
    printf("author: %s\n", book->author);
    printf("title: %s\n", book->title);
    printf("color: %s\n", colornames[book->color]);
}

int
main(void)
{
    struct Book book1;

    getInfo(&book1);
    showInfo(&book1);

    return 0;
}

推荐阅读