C++动态分配空间实例
#include<stdio.h>#include<conio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef struct
{
int *elem;
int length;
int listsize;
}SqList;
int InitList_Sq(SqList&L)
{
L.elem=(int*)malloc(LIST_INIT_SIZE*sizeof(int));
if(!L.elem)
exit(OVERFLOW);
L.length=0;
L.listsize=LIST_INIT_SIZE;
return OK;
}
int CreateList_Sq(SqList&L)
{
int i;
for(i=0; i<L.length;i++)
{ printf("Input the datas:");
scanf("%d",&L.elem
}
return OK;
}
int ListInsert_Sq(SqList&L,int i,int e)
{
int *p,*q,*newbase;
if((i<1)||(i>L.length+1))
return ERROR;
if(L.length>=L.listsize)
{
newbase=(int*)realloc(L.elem,(L.length+LISTINCREMENT)*sizeof(int));
if(!newbase)
exit(OVERFLOW);
L.elem=newbase;
L.listsize+=LISTINCREMENT*sizeof(int);
}
q=&(L.elem
for(p=&L.elem[l.length-1];p>=q;--p)
*(p+1)=*p;
*q=e;
L.length++;
return OK;
}
void main()
{
int i,n,e;
SqList L;
InitList_Sq(L);
printf("\nInput the length of the list L:");
scanf("%d",&n);
L.length=n;
CreateList_Sq(L);
printf("Input the Insert date:");
scanf("%d",&e);
printf("Input the insert location:");
scanf("%d",&i);
if(ListInsert_Sq(L,i,e))
{
printf("Output the datas:");
for(i=0;i<L.length;i++)
printf("%d",L.elem
}
else
printf("Can't insert the data!");
}