C++基础:二维数组动态的申请内存和释放内存

使用二维数组的时候,有时候事先并不知道数组的大小,因此就需要动态的申请内存。常见的申请内存的方法有两种:malloc/free 和 new/delete。

一、malloc/free

(1)申请一维数组

void dynamicCreate1Array()
{
int m;
int i;
int *p; cout<<("please input the length of data:");
cin >> m; p = (int*)malloc(sizeof(int)*m);//动态开辟 cout << "please input data" << endl;
for (i = ; i < m; i++)
cin >> p[i]; cout << "data is :";
for (i = ; i < m; i++)
cout << p[i] << endl;
free(p);
}

(2)申请二维数组

void dynamicCreate2Array()
{
int m, n;
int i, j;
int **p; printf("please input the row and col:");
cin >> m >> n;
//scanf("%d%d", &m, &n); p = (int**)malloc(sizeof(int*)*m); //开辟行 for (i = ; i < m; i++)
{
*(p + i) = (int*)malloc(sizeof(int)*n);//开辟列
}
//输入数据
printf("please input data:");
for (i = ; i < m; i++)
for (j = ; j < n; j++)
cin >> p[i][j];
//输出数据
for (i = ; i < m; i++)
{
for (j = ; j < n; j++)
{
cout << p[i][j];
}
cout << endl;
}
//释放开辟的二维空间
for (i = ; i < m; i++)
free(*(p + i));
}

二、new/delete

(1)申请一维数组

void DynamicCreate1Array()
{
int len;
int i; cout << "please input the length of data: ";
cin >> len; int *p = new int[len]; cout << "please input data: ";
for (int i = ; i < len; i++)
cin >> p[i]; cout << "data is " << endl;
for (i = ; i < len; i++)
cout <<p[i] << endl; delete[] p;
}

(2)申请二维数组

void DynamicCreate2Array()
{
int m, n;
int i;
cout << "input row and col: ";
cin >> m >> n; //动态开辟空间
int **p = new int*[m]; //开辟行
for (int i = ; i < m; i++)
p[i] = new int[n]; //开辟列 cout << "input data: ";
for (i = ; i < m; i++)
for (int j = ; j < n; j++)
cin >> p[i][j]; cout << "output: " << endl;
for (i = ; i < m; i++)
{
for (int j = ; j < n; j++)
cout << p[i][j]<<" ";
cout << endl;
} //释放开辟的资源
for (i = ; i < m; i++)
delete[] p[i];
delete[] p; }

注:另一种方法:

row:行

col:列

unsigned int **ppPathes;

*ppPathes = (unsigned int *)calloc(row * col, sizeof(unsigned int));

使用malloc:

*ppPathes = (unsigned int *)malloc(sizeof(unsigned int )*(PathNumTemp) * (pathLenTemp + 1));

上一篇:java中outer的使用


下一篇:HDU 2795 Billboard(区间求最大值的位置update的操作在query里做了)