关于c语言结构体(struct)的问题

来源:百度知道 编辑:UC知道 时间:2024/05/12 06:02:03
#include "stdio.h"
struct stu{
char *name;
char *sex;
int score;
}man[3];
main()
{
struct stu *p=man;
void getregist();
void print();
getregist(p);
print(p);
}
void getregist(struct stu *p)
{
puts("input the name:");
gets(p->name);
puts("input the sex:");
gets(p->sex);
puts("input the score:");
scanf("%d",&p->score);
getch();

}
void print(struct stu *p)
{
puts(p->name);

puts (p->sex);
printf ("%d",p->score);
}
程序的目的在于利用函数互动的输入结构的成员的值,以及最终把它输出.

但在运行时却得不到预期结果,在输入了第二个成员(sex)的值后,第一个成员(name)的值也被改变成第二个成员的值.

希望高手给我解答.
补充1:在turbo c 2.0下完全可以通过编译.
另外声明时在turbo c下应该不用声明形参的.
结构指针成员需没初始化,但之后应该可以允许用户手动输入呀,需然会有些危险但应该不会通不过编译.
楼下的代码可以得到预期的效果,但我还是想知道我的为什么不能!

你的程序VC++6.0下根本编译通不过去。
错误1:
函数实现时写的如下:
void getregist(struct stu *p)
void print(struct stu *p)
声明时写的如下:
void getregist();
void print();
形参个数不同。
错误2:
struct stu{
char *name;
char *sex;
int score;
}man[3];
内name和sex指针未初始化,指针在指向的内存不确定时就使用,指针使用异常。
更改如下:
#include "stdio.h"
#include <conio.h>
struct stu
{
char name[20];
char sex[20];
int score;
}man[3];

main()
{
struct stu *p=&man[0];
void print(struct stu *p);
void getregist(struct stu *p);
getregist(p);
print(p);
return 0;
}
void getregist(struct stu *p)
{
puts("input the name:");
gets(p->name);
puts("input the sex:");
gets(p->sex);
puts("input the score:");
scanf("%d",&p->score);
getch();
}

void print(struct stu *p)