动态数组根据用户的需要开创空间 避免造成空间的浪费
#include<stdio.h> #include<stdlib.h> typedef struct { int *parrary; int size; }array; array size(int intsize); void afree(int *p); int bigsmall(array *a); int *at(array *a,int index); void addtion(array *a,int add); void main() { int i; printf("请输入你需要开辟的空间大小(int)"); int b; scanf("%d",&b); array a=size(b); printf("已经开辟了%d个字节\n",bigsmall(&a)); printf("address:%p\n",a.parrary); int number=0; while(1) { scanf("%d",at(&a,number++)); if(number==5) { break; } }printf("%d",*(at(&a,7))); afree(a.parrary); } array size(int intsize) { array a; a.size=intsize; a.parrary=(int*)malloc(sizeof(int)*intsize); a.size=intsize; return a; } void afree(int *p) { free(p); } int bigsmall(array *a) { return a->size; } int *at(array *a,int index) { if(index>a->size) { addtion(a,1); } return &(a->parrary[index]); } void addtion(array *a,int add) { int *p=(int*)malloc((int)(a->size+add)); int i; for(i=0;i<=a->size;i++) { p[i]=a->parrary[i]; } free(a->parrary); a->parrary=p; a->size+=add; }