-2

I am trying to learn structures and the below code is having some sort of error, not logical but just shows up while execution saying, the file has stopped working. Occurs right after gets(s2.name)

#include<stdio.h>
struct student
{
  char *name;
  float mark1,mark2,mark3;
  float total;
};
int main()
{
struct student s1,s2,s[3];
s1.mark1=6;s1.mark2=7;s1.mark3=8;
s1.total = s1.mark1+s1.mark2+s1.mark3;
printf("\nEnter the name of s2 : ");
gets(s2.name);
/*when above line is inserted program hangs and code below does not execute*/
puts(s2.name);
s1.name = "shanky";
puts(s1.name);
getch();
return 0;
}

No compilation error obviously. Using gcc compiler

shanky
  • 1
  • 2

1 Answers1

4

You forgot to allocate memory for the name member of the struct. It is a pointer, but unless you malloc() some memory, you have no idea where it points to.

Try something like s2.name = malloc(80). Make sure you check the return value, and note that gets() is unsafe. Don't use that in production code. (or rather, don't use gets() at all).

Marc Balmer
  • 1,780
  • 1
  • 11
  • 18
  • `but unless you malloc() some memory`..how about assigning a pointer to another statically allocated variable? – Sourav Ghosh Jan 14 '17 at 17:24
  • @SouravGhosh: that works for one structure variable; it rapidly becomes untenable when there's more than one variable of that type kicking around. – Jonathan Leffler Jan 14 '17 at 22:06