c - c中的输入输出结构函数错误

标签 c function struct

这段代码应该读取书籍信息,然后打印信息,但是我的函数有错误,void in_book(struct books z), void out_book(struct books z)

#include <stdio.h>

struct books{
int id;
float price;
char title[15];
char description[140];
};

void in_book(struct books z){
printf("Enter the title\n");
gets(z.title);
printf("Enter the description\n");
gets(z.description);
printf("Enter the id\n");
scanf("%d",&z.id);
printf("Enter the price\n");
scanf("%f",&z.price);
}

void out_book(struct books z){
printf("Title       : %s\n",z.title);
printf("Description : %s\n",z.description);
printf("Id          : %d\n",z.id);
printf("Price       : %.1f\n",z.price);
}

void main(){
struct books b1;
in_book(b1);
out_book(b1);
}

这是输出

Enter the title
book
Enter the description
a book
Enter the id
1234
Enter the price
55
Title :
Description :
Id : 0
Price : 0.0

最佳答案

您正在以按值调用的方式分配结构体每个字段的值,这意味着更改仅在每个函数中可见。如果要设置值以便主函数中的结构保存所有更改,则需要一个指向结构的指针:

struct books *b1 = malloc(sizeof(struct books));

然后传递指针:

in_book(b1);
out_book(b1);

修改函数如下:

void in_book(struct books *z){
    printf("Enter the title\n");
    gets(z->title);
    printf("Enter the description\n");
    gets(z->description);
    printf("Enter the id\n");
    scanf("%d",&z->id);
    printf("Enter the price\n");
    scanf("%f",&z->price);
}

void out_book(struct books *z){
    printf("Title       : %s\n",z->title);
    printf("Description : %s\n",z->description);
    printf("Id          : %d\n",z->id);
    printf("Price       : %.1f\n",z->price);
}

编辑:

您还应该查找主题“按值调用”和“按引用调用”。

关于c - c中的输入输出结构函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45405751/

相关文章:

c - 在 C 中如何使用大小写将枚举转换为字符串?

c - 给结构体数组赋值时进程返回-1073741819 (0xC0000005)

将可变长度结构复制到缓冲区

c++ - 为什么这个结构需要一个大小值?

c - 查找动态分配的 unsigned long long 数组的长度

c - 在 C 中使用 fork() 的打印行为

c - DOS 头表示为 C 数据结构

c++ - 函数在 lpc824 中返回错误值

javascript - typescript 函数定义: return nested object with keys looked-up from value array

c - 事先声明的功能