1 #include<iostream> 2 using namespace std; 3 4 int arrayInit(int size, int **outbuf) //一维数组的初始化 5 { 6 int *a = NULL; 7 a=(int*)malloc(sizeof(int)*(size+1)); 8 9 *outbuf = a; 10 11 return size; 12 } 13 14 int arrayEx(int *buf,int size,int preSize, int **outbuf) //一维数组的扩容 15 { 16 // int len = sizeof(buf)/sizeof(buf[0]); 17 int *a = NULL; 18 19 a = (int *)malloc(sizeof(int)*(size+1)); 20 21 for (int i = 0; i < preSize; i++) 22 { 23 a[i] = buf[i]; 24 } 25 26 *outbuf = a; 27 // free(a); //不能在这里释放指针 28 29 return size; 30 } 31 32 void ArrayFree(int *buf) //指针的释放 33 { 34 free(buf); 35 buf = NULL; 36 } 37 38 void main() 39 { 40 int exlen=0; 41 int size = 0; 42 int *buf; 43 int *outbuf=NULL; 44 45 size = arrayInit(10, &buf); //数组的初始化 46 47 for (int i = 0; i < size; i++) 48 { 49 buf[i]= i; 50 } 51 52 for (int i = 0; i < size; i++) 53 { 54 cout << buf[i] <<endl; 55 } 56 57 58 size = arrayEx(buf, 20, size, &outbuf); 59 60 cout << "扩后的数组内容" << endl; 61 for (int i =10 ; i < 20; i++) 62 { 63 outbuf[i] = i; 64 } 65 66 for (int i = 0; i < size; i++) 67 { 68 cout << outbuf[i] << endl; 69 } 70 71 72 cout << "数组大小为"<<_msize(outbuf)/sizeof(int) << endl; //_msize返回new,或malloc方式分配出来的内存大小 73 ArrayFree(buf); 74 ArrayFree(outbuf); 75 system("pause"); 76 }