C语言 段错误 编译没有错误 栈运行错误,找不到原因
#include <stdio.h>
#include <stdlib.h>
struct NODE
{
char name[30];
float score;
struct NODE * next;
};
struct STACK
{
struct NODE * top;
struct NODE *bottom;
};
struct STACK * CreateStack(void)
{
struct STACK *S =(struct STACK *)malloc(sizeof*S);
S->top=S->bottom=(struct NODE *)malloc(sizeof*S->top);
if (NULL==S->top)
{
printf("内存不足,分配失败\n");
exit(-1);
}
S->top->next=NULL;
return S;
}
int StackEmpty(struct STACK *S)
{
if (S->bottom==S->top)
{
return 1;
}
else
{
return 0;
}
}
struct NODE * Push(struct NODE * top)
{
struct NODE * node=(struct NODE *)malloc(sizeof*node);
if (NULL==node)
{
printf("内存不足,分配失败\n");
exit(-1);
}
node->score=-123456;
while (1)
{
printf("请输入学生姓名,成绩:");
scanf("%s %f",node->name,node->score);
while (getchar()!='\n');
if (node->score=-123456)
{
printf("输入的成绩不符合规范,请重新输入\n");
}
else
{
break;
}
}
node->next=top;
top=node;
return top;
}
void OutputStack(struct STACK *S)
{
struct NODE * move=S->top;
while (S->bottom!=move)
{
printf("[姓名:%s,成绩:%.1f]->",move->name,move->score);
move=move->next;
}
printf("[^]\n");
}
void GetTop(struct NODE * top)
{
printf("姓名:%s,成绩%.1f\n",top->name,top->score);
}
struct NODE * Pop(struct NODE * top)
{
struct NODE * buf;
buf=top;
top=top->next;
free(buf);
buf=NULL;
return top;
}
void DestroyStack(struct STACK *S)
{
while (!(StackEmpty(S)))
{
S->top=Pop(S->top);
}
}
int main(void)
{
int num;
int ret;
struct STACK *S;
printf("是否创建栈(Y/N):");
while (1)
{
char ch;
scanf("%c",&ch);
while (getchar()!='\n');
if ('Y'==ch || 'y'==ch)
{
S=CreateStack();
break;
}
else if ('N'==ch || 'n'==ch)
{
return 0;
}
else
{
printf("请重新输入(Y/N):");
}
}
printf("1、判栈空\n2、压栈\n3、输出整个栈\n4、取栈顶结点\n5、出栈\n6、销毁栈\n7、退出\n");
while (1)
{
num=-1;
printf("请输入操作号:");
scanf("%d",&num);
while (getchar()!='\n');
switch (num)
{
case 1:
{
ret=StackEmpty(S);
if (1==ret)
{
puts("栈为空");
}
else if (0==ret)
{
puts("栈为非空");
}
break;
}
case 2:
{
S->top=Push(S->top);
break;
}
case 3:
{
OutputStack(S);
break;
}
case 4:
{
GetTop(S->top);
break;
}
case 5:
{
if (!(StackEmpty(S)))
{
S->top=Pop(S->top);
printf("出栈成功\n");
}
else
{
puts("栈空,出栈失败");
}
break;
}
case 6:
{
DestroyStack(S);
puts("栈已销毁");
break;
}
case 7:return 0;break;
default:
{
puts("输入错误,请重新输入!");
}
}
}
return 0;
}
下面问题改了再说
#include <stdio.h>
struct stu
{
int num;
char *name;
char sex;
float score;
} boy[5] = {
{101, "Li ping", 'M', 45},
{102, "Zhang ping", 'M', 62.5},
{103, "He fang", 'F', 92.5},
{104, "Cheng ling", 'F', 87},
{105, "Wang ming", 'M', 58}};
void Fve(struct stu *ps)
{
int c = 0, i;
float ve, s = 0;
for (i = 0; i < 5; i++, ps++)
{
s += ps->score;
if (ps->score < 60)
c += 1;
}
printf("s=%f\n", s);
ve = s / 5;
printf("average=%f\ncount=%d\n", ve, c);
}
main()
{
struct stu *ps;
void Fve(struct stu * ps);
ps = boy;
Fve(ps);
}
执行结果:
s=345.000000
average=69.000000
count=2
[Thread 30236.0xa0b0 exited with code 26]
[Inferior 1 (process 30236) exited with code 032]