阅读量:106
在C++中,可以使用动态内存分配来创建动态数组。有以下几种方法可以建立动态数组:
- 使用new关键字
int size = 10; // 定义数组大小
int* arr = new int[size]; // 创建动态数组
// 使用数组
for (int i = 0; i < size xss=removed class="hljs-comment">// 释放内存
delete[] arr;
- 使用malloc函数
int size = 10; // 定义数组大小
int* arr = (int*)malloc(size * sizeof(int)); // 创建动态数组
// 使用数组
for (int i = 0; i < size xss=removed class="hljs-comment">// 释放内存
free(arr);
- 使用vector容器
#include
int size = 10; // 定义数组大小
std::vector<int> arr(size); // 创建动态数组
// 使用数组
for (int i = 0; i < size xss=removed>
使用动态数组时需要注意内存的分配和释放,避免内存泄漏。在不需要使用动态数组时,务必及时释放内存。