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 = 0; i < m; i++) cin >> p[i]; cout << "data is :"; for (i = 0; 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 = 0;