为什么我的结构不显示?
Why my structures do not display?
我正在研究这个结构内存分配。谁能帮我弄清楚为什么它会为作者、标题和 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
中再分配一本书。写进第二本书。 Return 来自 add_book
(泄漏填写的书)并返回到 main 中未触及的书。
然后你调用 print_records
,你从 main 传递这本书。然后立即创建另一本空书,打印它的详细信息并 return 泄漏另一本书)。
你从来没有接触过你在 main 中开始阅读的原书...
解决方法:去掉add_records
和print_records
.
中的b = (struct book*) malloc(sizeof(struct book));
行
我正在研究这个结构内存分配。谁能帮我弄清楚为什么它会为作者、标题和 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
中再分配一本书。写进第二本书。 Return 来自 add_book
(泄漏填写的书)并返回到 main 中未触及的书。
然后你调用 print_records
,你从 main 传递这本书。然后立即创建另一本空书,打印它的详细信息并 return 泄漏另一本书)。
你从来没有接触过你在 main 中开始阅读的原书...
解决方法:去掉add_records
和print_records
.
b = (struct book*) malloc(sizeof(struct book));
行