这段代码为什么输入值时会报错啊!!!

payen_1985 2008-01-13 10:43:08
#include <stdio.h>
#include <string.h>
struct student
{
char *name;
int Num;
int score;
};
void order(struct student *p,int n)
{
int i,j;
struct student temp;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if((*(p+i)).score<(*(p+j)).score)
{
temp=*(p+i);
*(p+i)=*(p+j);
*(p+j)=temp;
}
}
void find(struct student *p,char *name,int n)
{
int i;
printf("name: ");
puts(name);
for(i=0;i<n;i++)
if(strcmp((*(p+i)).name,name)==0) printf("Order: %d",i+1);
}
void main()
{
struct student s[30],*p=s;
int i;
char *name;
for(i=0;i<30;i++)
{
flushall();
gets(s[i].name);
scanf("%d%d",&s[i].Num,&s[i].score);

}
order(p,i);
printf("input a name");
gets(name);
printf(" * * * * * * * * * * Order Table * * * * * * * * * * \n");
printf(" No Name Num Score\n");
for(i=0;i<30;i++)
{
printf(" %d ",i+1);
puts(s[i].name);
printf(" %d %d\n",s[i].Num,s[i].score);
}
find(p,name,i);
}

请各位帮忙找下问题啊,当输入完第一项数据,一敲回车就报错!这是什么原因!!!
...全文
71 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
payen_1985 2008-01-13
  • 打赏
  • 举报
回复
哦。。 应该是,p内只能保存地址,如果没有指定指向那么给它赋的值没有保存的空间。。。
谢谢两位,结贴!
payen_1985 2008-01-13
  • 打赏
  • 举报
回复
是不是不能给一个没有指定指向的指针进行赋值,如:char *p; gets(p);
lori227 2008-01-13
  • 打赏
  • 举报
回复
char name[20];
tjltail 2008-01-13
  • 打赏
  • 举报
回复
struct   student 
{
char *name;
int Num;
int score;
};


声明的时候是分配了空间,是分配了struct的空间
而name指向的空间是没有分配的。

解决办法:name的大小固定,可以声明为数组,不固定可以动态分配。

struct student _test_student;

_test_student.name = (char*)malloc(sizeof(char)*size));
payen_1985 2008-01-13
  • 打赏
  • 举报
回复
申明的时候不是自动分配内存的吗?要怎么改???
lori227 2008-01-13
  • 打赏
  • 举报
回复
struct student
{
char *name;
int Num;
int score;
};

char *name;这里只声明了一个指针,并没有分配内存空间!

70,037

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧