1、使用固定列数的原始数组
当将二维数组传递给函数时,如果使用固定列数的原始数组(即非指针方式),必须在函数参数中指定列的大小,这样编译器才能正确地计算内存偏移。
#include <iostream> const int COLS = 3; // 函数声明,必须指定列数 void printMatrix(int matrix[][COLS], int rows) { for (int i = 0; i < rows; ++i) { for (int j = 0; j < COLS; ++j) { std::cout << matrix[i][j] << " "; } std::cout << std::endl; } } int main() { int data[2][COLS] = { {1, 2, 3}, {4, 5, 6} }; printMatrix(data, 2); // 传递行数 return 0; }
2、使用指针并传入列数
将二维数组传递给函数时,如果使用指针方式并传入列数,需要手动管理每行的列数信息。
#include <iostream> using namespace std; // 函数声明,传入二维数组指针和列数 void printArray(int* arr, int rows, int cols) { for (int i = 0; i < rows; ++i) for (int j = 0; j < cols; ++j) cout << "arr[" << i << "][" << j << "] = " << *(arr + i * cols + j) << endl; } int main() { int array[2][3] = { {1, 2, 3}, {4, 5, 6} }; // 将二维数组地址和列数传入函数 printArray(&array[0][0], 2, 3); return 0; }
3、使用 std::vector(推荐用于灵活大小)
将二维数组传递给函数推荐使用 std::vector<std::vector<T>>
,因为它提供更大的灵活性(支持动态大小、容器特性等)。
#include <iostream> #include <vector> using namespace std; // 接收二维 vector 的函数 void printMatrix(const std::vector<std::vector<int>>& matrix) { for (const auto& row : matrix) { for (int val : row) std::cout << val << " "; std::cout << std::endl; } } int main() { // 创建一个 3x4 的二维数组(vector 形式) std::vector<std::vector<int>> matrix = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; // 传递给函数 printMatrix(matrix); return 0; }
4、使用模板(通用写法)
为了通用地将任意大小的二维数组传递给函数,可以使用模板来实现。
#include <iostream> using namespace std; template <typename T, size_t ROWS, size_t COLS> void printMatrix(T (&matrix)[ROWS][COLS]) { for (size_t i = 0; i < ROWS; ++i) { for (size_t j = 0; j < COLS; ++j) { std::cout << matrix[i][j] << " "; } std::cout << "\n"; } } int main() { int matrix1[2][3] = {{1, 2, 3}, {4, 5, 6}}; double matrix2[3][2] = {{1.1, 2.2}, {3.3, 4.4}, {5.5, 6.6}}; std::cout << "Matrix 1:\n"; printMatrix(matrix1); std::cout << "\nMatrix 2:\n"; printMatrix(matrix2); return 0; }