阅读量:75
在C++中,可以通过指针或引用的方式将动态二维数组传递给函数。
- 使用指针传递动态二维数组:
void function(int** array, int rows, int cols) {
// 访问数组元素
for(int i = 0; i < rows class="hljs-keyword">for(int j = 0; j < cols class="hljs-string">" ";
}
cout << endl class="hljs-function">int main() {
int rows = 3;
int cols = 3;
// 创建动态二维数组
int** arr = new int*[rows];
for(int i = 0; i < rows xss=removed class="hljs-keyword">new int[cols];
}
// 初始化数组
for(int i = 0; i < rows class="hljs-keyword">for(int j = 0; j < cols xss=removed class="hljs-comment">// 调用函数
function(arr, rows, cols);
// 释放内存
for(int i = 0; i < rows class="hljs-keyword">delete[] arr[i];
}
delete[] arr;
return 0;
}
- 使用引用传递动态二维数组:
void function(int**& array, int rows, int cols) {
// 访问数组元素
for(int i = 0; i < rows class="hljs-keyword">for(int j = 0; j < cols class="hljs-string">" ";
}
cout << endl class="hljs-function">int main() {
int rows = 3;
int cols = 3;
// 创建动态二维数组
int** arr = new int*[rows];
for(int i = 0; i < rows xss=removed class="hljs-keyword">new int[cols];
}
// 初始化数组
for(int i = 0; i < rows class="hljs-keyword">for(int j = 0; j < cols xss=removed class="hljs-comment">// 调用函数
function(arr, rows, cols);
// 释放内存
for(int i = 0; i < rows class="hljs-keyword">delete[] arr[i];
}
delete[] arr;
return 0;
}
无论是使用指针还是引用,都可以在函数中对动态二维数组进行操作。需要注意的是,在传递动态二维数组给函数后,需要在函数结束后手动释放内存,以避免内存泄漏。