- 实验环境win7操作系统下vs2017
- 定义结构体用于存放教练信息
struct mycoach { char name[60]; int age; char skills[60]; };
- 定义线性表存放教练信息
struct seqlist { struct mycoach* mch[10];//这里要用指针,否则操作系统将无法得知分配多少内存, int length; int lastid; };
- 赋值测试,确保可以对线性表的每一元素顺利赋值
void main() { struct seqlist* slist; slist = (struct seqlist*)malloc(sizeof(struct seqlist)); slist->mch[0] = (struct mycoach*)malloc(sizeof(struct mycoach)); strcpy(slist->mch[0]->name, "陈培昌"); slist->mch[0]->age = 22; strcpy(slist->mch[0]->skills,"泰拳,散打"); printf("姓名:%s ", slist->mch[0]->name); printf("年龄:%d ", slist->mch[0]->age); printf("武技:%s ", slist->mch[0]->skills);
//及时释放内存空间是必要的 free(slist->mch[0]); slist->mch[0] = NULL; free(slist); slist =NULL; system("pause"); }
输出结果:
- 封装过的一个版本
#define _CRT_SECURE_NO_WARNINGS #define maxsize 1024 #include<stdio.h> #include<stdlib.h> #include<string.h> struct mycoach { char name[60]; int age; char skills[60]; }; struct seqlist { struct mycoach* mch[maxsize]; int length; int lastid; }; int initlist(struct seqlist * l) { int length,j=0; printf("初始化,准备输入几个档案信息 "); scanf("%d",&length); for (j=0;j<length;j++) { l->mch[j] = (struct mycoach*)malloc(sizeof(struct mycoach)); printf("输入教练姓名 "); scanf("%s", &l->mch[j]->name); printf("输入教练年龄 "); scanf("%d", &l->mch[j]->age); printf("输入教练武技 "); scanf("%s", &l->mch[j]->skills); } printf("j的值是:%d ",j); l->lastid = j; printf("输入完毕~黎塞留主教大人!"); } void printinfo(struct seqlist* slist) { int length = slist->lastid,j=0; for (j=0;j<length;j++) { printf("姓名:%s ", slist->mch[j]->name); printf("年龄:%d ", slist->mch[j]->age); printf("武技:%s ", slist->mch[j]->skills); free(slist->mch[j]); slist->mch[j] = NULL; printf("%s ", "======================"); } }
主函数调用
void main() { struct seqlist * l; l = (struct seqlist*)malloc(sizeof(struct seqlist*)); initlist(l); printf(" %s ", "======================"); printinfo(l); system("pause"); }
输出结果: