RT,这是个简单的代码处理数组插入,想在插入时判断此时数组是否将满,如果是就将数组扩大的原来的2倍。
不明白为什么int *newspace=(int*)malloc(size*sizet);有什么错误,如果把size改成一个定值就可以运行且结果正确,难道是malloc的bug?
#include <stdlib.h>//malloc#include <string.h>//memset#include <stdio.h>//printf#define MAXIMUM 100struct SeqList{ int n; int * array; int max; };typedef struct SeqList *PSeqList;PSeqList createSeqList(int size){ PSeqList ptrSeqList=(PSeqList)malloc(sizeof(struct SeqList)); if(ptrSeqList==NULL){ return NULL; } ptrSeqList->n=0; ptrSeqList->array=(int*)malloc(size*sizeof(int)); ptrSeqList->max=size; return ptrSeqList; }int insertElement(int pos, int val, PSeqList pSeqList){ if(pSeqList==NULL) return -1; if(pSeqList->n==pSeqList->max){ int size=pSeqList->n<<1; int sizet=sizeof(int); int *newspace=(int*)malloc(size*sizet); memset((void*)newspace,0,size*sizeof(int)); int i=0; while(i++<pSeqList->max){ newspace[i]=pSeqList->array[i]; } free(pSeqList->array); pSeqList->array=newspace; pSeqList->max<<=1; } if(pSeqList->n==0){ pSeqList->array[0]=val; pSeqList->n++; return 0; } int i; for(i=pSeqList->n;i>=pos;--i){ pSeqList->array[i+1]=pSeqList->array[i]; } pSeqList->n++; pSeqList->array[pos]=val; }void printArray(PSeqList ptrSeqList){ printf("n: %d\n",ptrSeqList->n); printf("max: %d\n",ptrSeqList->max); int i=0; for(i;i<ptrSeqList->n;++i){ printf("%d ",ptrSeqList->array[i]); } }int main(int argc, char*argv[]){ PSeqList ptrSeqList=createSeqList(5); printArray(ptrSeqList); int i=0; for(i=0;i<10;++i){ insertElement(i,i,ptrSeqList); } printArray(ptrSeqList); insertElement(5,110,ptrSeqList); printArray(ptrSeqList); return 0; }