Click here to Skip to main content
15,891,930 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
C++
struct book
{
	char name[50];
	char author[50];
	int page;
	float price;
};
int main()
  {
  	 struct book *x;
  	 printf("name : ");
  	 gets(x->name);
  	 printf("author : ");
  	 gets(x->author);
  	 printf("page : ");
  	 scanf("%d",&x->page);
  	 printf("price : ");
  	 scanf("%f",&x->price);
  	 printf("\n%s\t%s\t%d\t%f",x->name,x->author,x->page,x->price);
  	 getch();
  	 return 0;
  }

this code is not working properly and giving a segmentation fault
Posted

I'm not surprised it gives a segmentation fault. In main you have;
C++
  	 struct book *x;
  	 printf("name : ");
  	 gets(x->name);
...

So you have created the pointer x but it does not point to anything, hence the seg fault. You need to initialise it so that it points to an actual memory structure. This is done by a call to malloc thus:
C++
struct book *x;
    // allocate a new book structure on the heap
    x = (struct book *)malloc(sizeof(struct book));
printf("name : ");
gets(x->name);
 
Share this answer
 
You didn't initialize the structure pointer x. I guess you're using C++ by seeing your question's tags. Do it in this way.
C++
struct book *x;
x = new book;
printf("name : ");
.....
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900