我正在研究這種結構內存分配。有人可以幫我弄清楚爲什麼它會顯示作者,標題和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