gpt4 book ai didi

c - 为什么我的结构不显示?

转载 作者:行者123 更新时间:2023-11-30 19:42:02 25 4
gpt4 key购买 nike

我正在研究这个结构的内存分配。有人能帮我弄清楚为什么它显示作者、标题和 ID 为空白吗?输入不会继续传递到打印函数上,我不明白为什么。这是我的代码:

#include <stdio.h>
#include <stdlib.h>

struct book{
char author[16];
char title[16];
int id;
};

int i, n;

void add_records(struct book *b);
void print_records(struct book *b);

int main(int argc, char *argv) {

struct book *someBook;
someBook = (struct book*) malloc(sizeof(struct book));
add_records(someBook);
print_records(someBook);

return 0;
}


void add_records(struct book *b){
fprintf(stderr, "How many items do you want to add\n");
scanf("%d", &n);
b = (struct book*) malloc(n * sizeof(struct book));

for(i = 0; i < n; i++){
fprintf(stderr,"add author\n");
scanf("%s", (b + i)->author);
fprintf(stderr,"add title\n");
scanf("%s",(b+i)->title);
fprintf(stderr,"add Id: \n");
scanf("%d", &(b+i)->id);
}
}

void print_records(struct book *b){
b = (struct book*) malloc(sizeof(struct book));
for(i = 0; i < n; ++i){
printf("Author: %s\t Title: %s\t Id: %d\n", (b+i)->author,(b+i)->title,(b+i)->id);
}
}

最佳答案

您在 main 中分配一本书,并将其传递给 add_records。然后在add_records中分配另一本书。写进第二本书。从 add_book 返回(泄漏已填写的书)并返回到 main 中未触及的书。

然后调用 print_records,从 main 传递这本书。然后立即创建另一本空书,打印其详细信息并返回泄漏另一本书)。

你从来没有碰过你在主要内容中开始阅读的原书...

解决方案:删除 add_records 中的 b = (struct book*) malloc(sizeof(struct book)); 行并打印记录

关于c - 为什么我的结构不显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32959898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com