我正在尝试学习结构,下面的代码出现了某种错误,不是合乎逻辑的,只是在执行时显示,文件已停止工作。在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;
}
显然没有编译错误。使用gcc编译器
答案 0 :(得分:4)
您忘记为结构的名称成员分配内存。它是一个指针,但除非你的malloc()有一些内存,否则你不知道它指向的位置。
尝试类似s2.name = malloc(80)的内容。确保检查返回值,并注意gets()是不安全的。不要在生产代码中使用它。 (或者更确切地说,根本不使用gets())。