2015-10-06 125 views
-1

我正在研究这种结构内存分配。有人可以帮我弄清楚为什么它会显示作者,标题和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); 
} 
} 
+0

C是传递值。更改被调用者中的函数参数不会更改调用者中的相应变量(如果有)。 – EOF

回答

0

您在main中分配一本书,将它传递给add_records。然后在add_records分配另一本书。写入第二本书。从add_book返回(泄漏填满的书)并返回到主要的未触动的书。

然后你打电话给print_records,你从那里通过这本书。然后立即创建另一本空白书,打印它的细节并返回泄漏另一本书)。

你从来没有一次触摸你的主开始与原书...

解决方案:add_recordsprint_records摆脱b = (struct book*) malloc(sizeof(struct book));线。

+0

谢谢John3136!它总是小事。我认为我必须在功能级别和主级别上动态分配内存。 –