用malloc分配动态二维数组

假设我需要一个nrows、 ncolumns数组,则可以用以下几种方法动态分配空间:


1. 动态数组的成员都可以用正常的数组下标 Array[i][j]

 


2. 让数组的内容连续, 但在后来重新分配列的时候会比较困难, 得使用一点指针算术:

 


3. 同一个单独的动态分配的一维数组来模拟二维数组:

 


在C++中,可以使用`malloc`函数动态分配二维数组。以下是几种常见的方法: ### 方法一:使用`malloc`分配指针数组和每一行的数据 ```cpp #include <iostream> #include <cstdlib> int main() { int rows = 3; int cols = 5; // 使用 malloc 分配指针数组 int** arr = (int**)malloc(rows * sizeof(int*)); if (arr == nullptr) { std::cerr << "Memory allocation failed!" << std::endl; return 1; } // 为每一行分配内存 for (int i = 0; i < rows; ++i) { arr[i] = (int*)malloc(cols * sizeof(int)); if (arr[i] == nullptr) { std::cerr << "Memory allocation failed!" << std::endl; // 释放之前分配的内存 for (int j = 0; j < i; ++j) { free(arr[j]); } free(arr); return 1; } } // 初始化数组 for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { arr[i][j] = i * cols + j; } } // 访问数组 for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { std::cout << arr[i][j] << " "; } std::cout << std::endl; } // 释放内存 for (int i = 0; i < rows; ++i) { free(arr[i]); } free(arr); return 0; } ``` 这种方法先使用`malloc`分配一个指针数组,每个指针指向一行的内存。然后再为每一行分配内存。 ### 方法二:结合`malloc`和`new` ```cpp #include <iostream> #include <cstdlib> int main() { int len = 100; int** dp = (int**)malloc(sizeof(int*) * (len + 1)); if (dp == nullptr) { std::cerr << "Memory allocation failed!" << std::endl; return 1; } for (int i = 0; i <= len; ++i) { dp[i] = new int[4]; } // 使用数组... // 释放内存 for (int i = 0; i <= len; ++i) { delete[] dp[i]; } free(dp); return 0; } ``` 此方法中,`malloc`分配指针数组,`new`分配每一行的数据。 ### 方法三:使用同一个单独的动态分配的一维数组来模拟二维数组 ```cpp #include <iostream> #include <cstdlib> int main() { int nrows = 3; int ncolumns = 5; // 分配一维数组 int* Array = (int*)malloc(nrows * ncolumns * sizeof(int)); if (Array == nullptr) { std::cerr << "Memory allocation failed!" << std::endl; return 1; } // 初始化数组 for (int i = 0; i < nrows; ++i) { for (int j = 0; j < ncolumns; ++j) { Array[i * ncolumns + j] = i * ncolumns + j; } } // 访问数组 for (int i = 0; i < nrows; ++i) { for (int j = 0; j < ncolumns; ++j) { std::cout << Array[i * ncolumns + j] << " "; } std::cout << std::endl; } // 释放内存 free(Array); return 0; } ``` 这种方法通过一个一维数组模拟二维数组,通过计算索引来访问元素。
评论 5
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值