获取分段转储错误,在运行代码时,它会正确编译。 当我运行程序时,它会要求我输入 输入名称数组的值后,会导致分段错误。 请帮我解决无错误的解决方案。
#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;
}
答案 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;
}