结构体数组
#include <stdio.h>#include <stdlib.h>
#define NUM 3
int main()
{
struct person
{
char *name;
char phone;
};
struct person man;
int i;
for(i = 0; i < NUM; i++)
{
printf("input name : \n");
gets(man.name);
printf("input phone : \n");
gets(man.phone);
}
printf("\n\tname\t\t\t\t\tphone\n\n");
for(i = 0; i < NUM; i++)
{
printf("%20s\t\t\t%20s\n", man.name, man.phone);
}
system("pause");
return 0;
}
该代码运行时,循环到一半循环不下去。这个是什么情况?????
char *name;没有分配用来保存字符串的空间
char *name = (char *)malloc(20)
还是字符数组好 #include <stdio.h>
#include <stdlib.h>
#define NUM 3
int main()
{
struct person
{
char name;
char phone;
};
struct person man;
int i;
for(i = 0; i < NUM; i++)
{
printf("input name : \n");
gets(man.name);
printf("input phone : \n");
gets(man.phone);
}
printf("\n\tname\t\t\t\t\tphone\n\n");
for(i = 0; i < NUM; i++)
{
printf("%20s\t\t\t%20s\n", man.name, man.phone);
}
system("pause");
return 0;
} 结构体内嵌套一级指针(比如本题的 char *name)很麻烦,要给它分配空间,最后还要释放,所以结构体内类似 姓名这样的就象楼上二位所说用字符数组比较方便。
页:
[1]