2016-11-15 89 views
2

在运行代码时得到分段转储错误,但它会正确编译。 当我运行该程序时,它要求我输入 向名称数组输入值后,会导致分段错误。 请帮助我使用无错解决方案。C中出现错误“分段错误(核心转储)”

#include<stdio.h> 

struct book 
{ 
char name[20]; 
char author[20]; 
int price; 
}; 

struct pages 
{ 
int page; 
struct book b1; 
} *p; 

int main() 
{ 
printf("\nEnter the book name , author , price, pages\n"); 
scanf("%s %s %d %d",p->b1.name,p->b1.author,&p->b1.price,&p->page); 

printf("The entered values are\n"); 

printf("The name of book=%s\n",p->b1.name); 
printf("The author of book=%s\n",p->b1.author); 
printf("The price of book=%d\n",p->b1.price); 
printf("The pages of book=%d\n",p->page); 



return 0; 


} 

回答

3

你还没有为p分配的内存。添加代码为p分配内存并在从main返回之前释放该内存。使用

int main() 
{ 
    p = malloc(sizeof(*p)); 

    printf("\nEnter the book name , author , price, pages\n"); 
    scanf("%s %s %d %d",p->b1.name,p->b1.author,&p->b1.price,&p->page); 

    ... 

    free(p); 
    return 0; 
} 
+0

它'p'是一个指向结构的指针,当我使用malloc分配内存后,但如果我使用'p'作为结构'页'的变量(不是指针),那么我不' t需要使用malloc分配内存。为什么? –

+0

@AuuragVishwa,那么'p'是一个对象。对象的内存由运行时环境创建。使用'malloc'不需要为定义为对象的变量创建内存。 –