链表是怎么发展来的2
在上一篇博客中,其中的程序缺点明显,存在浪费空间的问题,人名限制不太严格不满足需求,人员总数量对有些公司来说太小。
总结:数据表示不够灵活,程序在编译时就已经确定了所需的内存空间大小,对此如果能在程序运行时确定会更好。
- 解决方法:使用动态内存分配来表示数据,解决思路如下图:
#include <stdio.h>
#include <string.h>
#define NAME_SIZE 20//人名字符大小
typedef struct peoplecard
{
char name[NAME_SIZE];
int age;
}
char* manage_gets(char str[],int len_limt);
int main(void)
{
int pnum, i;
int j;
peoplecard* peol;
printf(“ Enter the people num:\n”);
scanf(“%d”,&n);
peol = (peoplecard*)malloc(n*sizeof(peoplecard));
puts(“Enter first peol name”);//输入第一个人员的名字
while((i < n)&&( manage_gets(peol[i].name, NAME_SIZE)!=NULL) &&( peol[i].name[0]!=’\0’))
{
puts(“Enter your age <0-200>:”);
scanf(“%d”,& peol[i++].age);
while(getchar()!=’\n’)
{
continue;
}
puts(“Enter next people name(empty line to stop):”);
}
if(i==0)
{
puts(“No data enter!”);
}
else
{
printf(“ Here is the people list:\n”);
for(j=0;j<i;j++)//是小于i而不是i+1,因为在前面i会多加一次。
{
printf(“people :%s, age:%d\n”, peol[j].name, peol[j].age);
}
printf(“end!\n”);
}
return 0;
}
char* manage_gets(char str[],int len_limt)
{
char* ret_val;
char* find;
ret_val = fgets(str,len_limt,stdin);
if(ret_val)
{
find = strchr(str,’\0’);
if(find)
{
*find = ‘\0’;
}
else
{
while(getchar()!=’\n’)
{
continue;
}
}
}
return ret_val;
}