2

Getting segmentation dumped error,while running the code, it compiles properly though. When i run the program it asks me for the input After entering a value to the name array, it results into segmentation fault. Please help me with the error free solution.

#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;


}

1 Answers1

3

You haven't allocated memory for p. Add code to allocate memory for p and deallocate that memory before returning from main. Use

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;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • It worked when 'p' is a pointer to the structure after i assigned memory using malloc, but if i use 'p' as the variable (not pointer) to the structure 'pages' then i don't need to assign the memory using malloc .Why is it so? – Anurag Vishwa Nov 15 '16 at 05:16
  • @AnuragVishwa, then `p` is an object. Memory for the object is created by the run time environment. Use of `malloc` is not necessary to create memory for variables that are defined as objects. – R Sahu Nov 15 '16 at 05:19