C语言动态创建数组并增加数组长度
#include <iostream>
#include<stdlib.h>
using namespace std;
#define InitSize 10
typedef struct{
int *data;
int MaxSize;
int length;
}Customer;
void InitList(Customer customer){
customer.data = (int *)malloc(sizeof(int)*InitSize);
customer.length=0;
customer.MaxSize=InitSize;
cout<<customer.length<<endl;
}
//使用malloc函数动态增加数组长度,即重新开辟一段指定长度的地址空间,将原来的数组元素复制至新的数组当中
//最后释放原来的内存空间
void InsertList(Customer customer,int n){
int *q = customer.data;
customer.data = (int *)malloc(sizeof(int)*(InitSize+n));
cout<<customer.length<<endl;
for(int i=0;i<customer.length;i++){
customer.data[i]=q[i];
}
customer.MaxSize = customer.MaxSize+n;
free(q);
}
int main()
{
Customer customer;
InitList(customer);
InsertList(customer,5);
return 0;
}