c - 如何打印结构的元素?
问题描述
我制作了这个程序来保存关于一本书的信息,但它不能正确打印
#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;
}
原则上,程序应该很好地保存它们,因为如果我将打印放在保存数据的函数中,它们确实可以正确打印。但是通过模块化程序,它就停止了。
解决方案
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;
}
推荐阅读
- python - 无法在 Python 3 中打开文本文件:Unicode 错误
- c - 如何使用函数指针编写函数名?
- angular - FormArray.value 返回一个空数组
- python - Python - 为什么我的合并排序版本会破坏性地对输入数组进行排序?
- python - 字典键值对是否可以自行切换和删除,如下例所示?
- docker - 带有 traefik 的 docker 容器,尤其是浏览器 URL 中的端口
- sql - SQL Checksum_agg(Checksum(columns)) 为不同的数据集返回相同的值
- wpf - 如何从 WPF MSIX 应用程序(桌面桥)更改 Windows 10 颜色设置?
- angular - 如果 Observable 为真,则获取 Observable 值,否则打印字符串
- asp.net-core - 过滤掉 ILogger 日志