c数据结构课本上有关顺序表基础操作的代码运行不了,我提取了其中有问题的一部分,怎么改啊
这部分代码只有初始化,空表情况下头插5个数,运行不了。(l.length在空表下等于0啊,那么还怎样运行p=&(l.elem[l.length-1])呢?)
帮忙把这段代码改正确
程序代码:
#include<stdio.h> #include<malloc.h> typedef int Status; #define INITSIZE 10 #define INCREMENT 2 typedef int elementype; struct sqlist { elementype *elem; int length; int listsize; }; void initlist(sqlist &l) { l.elem=(elementype*)malloc(INITSIZE*sizeof(elementype)); if(!l.elem) { printf("overflow"); } else { l.length=0; l.listsize=INITSIZE; printf("ok\n"); } } Status listinsert(sqlist l,int i,elementype e) { elementype *p,*q,*newbase; if(i<1||i>l.length+1) { printf("位置非法"); return(0); } if(l.length>=l.listsize) { newbase=(elementype*)realloc(l.elem,(l.listsize+INCREMENT)*sizeof(elementype)); if(!newbase) { printf("内存扩展失败"); return(0); } l.elem=newbase; l.listsize+=INCREMENT; } q=&(l.elem[i-1]); for(p=&(l.elem[l.length-1]);p>=q;--p) *(p+1)=*p; *q=e; ++l.length; printf("ok\n"); return(1); } void main() { Status i; int j,a; sqlist l; initlist(l); printf("初始L化后:l.elem=%u,l.length=%d,l.listsize=%d\n",l.elem,l.length,l.listsize); for(j=1;j<=5;j++) { printf("输入\n"); scanf_s("%d",&a); i=listinsert(l,1,a); } printf("插入5个数之后\n"); for(j=0;j<=4;j++) printf("*l.elem[%d]=%d\n",j,*(l.elem+j)); printf("l.elem=%u,l.length=%d,l.listsize=%d\n",l.elem,l.length,l.listsize); }
[ 本帖最后由 sanjianfei 于 2012-4-9 16:42 编辑 ]