我正在研究这种结构内存分配。有人可以帮我弄清楚为什么它会显示作者,标题和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);
}
}
C是传递值。更改被调用者中的函数参数不会更改调用者中的相应变量(如果有)。 – EOF