# 如何在 C++ 中将 2D 数组传递给函数

## 使用 `[]` 记号传递 2D 数组作为函数参数

``````#include <iostream>
#include <vector>
#include <iomanip>

using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::setw;

constexpr int size = 4;

void MultiplyArrayByTwo(int arr[][size], int len)
{
for (int i = 0; i < len; ++i) {
for (int j = 0; j < len; ++j) {
arr[i][j] *= 2;
}
}
}

int main(){
int c_array[size][size] = {{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 }};

cout << "input array\n";
for (int i = 0; i < size; ++i) {
cout << " [ ";
for (int j = 0; j < size; ++j) {
cout << setw(2) << c_array[i][j] << ", ";
}
cout << "]" << endl;
}

MultiplyArrayByTwo(c_array, size);

cout << "output array\n";
for (int i = 0; i < size; ++i) {
cout << " [ ";
for (int j = 0; j < size; ++j) {
cout << setw(2) << c_array[i][j] << ", ";
}
cout << "]" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
``````

``````input array
[  1,  2,  3,  4, ]
[  5,  6,  7,  8, ]
[  9, 10, 11, 12, ]
[ 13, 14, 15, 16, ]
output array
[  2,  4,  6,  8, ]
[ 10, 12, 14, 16, ]
[ 18, 20, 22, 24, ]
[ 26, 28, 30, 32, ]
``````

## 使用`&`符号传递 2D 数组作为函数参数

``````#include <iostream>
#include <vector>
#include <iomanip>

using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::setw;

constexpr int size = 4;

void MultiplyArrayByTwo(int (&arr)[size][size])
{
for (auto & i : arr) {
for (int & j : i)
j *= 2;
}
}

int main(){
int c_array[size][size] = {{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 }};

cout << "input array\n";
for (int i = 0; i < size; ++i) {
cout << " [ ";
for (int j = 0; j < size; ++j) {
cout << setw(2) << c_array[i][j] << ", ";
}
cout << "]" << endl;
}

MultiplyArrayByTwo(c_array);

cout << "output array\n";
for (int i = 0; i < size; ++i) {
cout << " [ ";
for (int j = 0; j < size; ++j) {
cout << setw(2) << c_array[i][j] << ", ";
}
cout << "]" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
``````

## 相关文章 - C++ Array

• 如何在 C++ 中循环遍历数组