无法将 2D 数组传递到 c++ 中的帮助程序函数中

Cannot pass 2d array into a helper function in c++

本文关键字:c++ 帮助程序 函数 2D 数组      更新时间:2023-10-16

当我创建一个辅助函数来打印当前 2D 数组的电路板时,我正在学习 c++ 并实现人生游戏。我似乎无法将数组传递到函数中,因为我收到一个错误,"候选函数不可行:第三个参数没有从'char [rows][cols]'到'char (*([cols]'的已知转换。如果有帮助,我正在使用 Xcode 作为 IDE。

void printArray(int rows, int cols, char board[rows][cols]){
for(int r = 0; r < rows; r++){
for(int c = 0; c < cols; c++){
cout << board[r][c];
cout << " ";
}
cout << "n";
}
}
int main(){
char board[5][5];
for(int r = 0; r < 5; r++){
for(int c = 0; c < 5; c++){
board[r][c] = 0;
}
}
printArray(5, 5, board);
return 0;
}

我尝试将参数切换到不同的东西,例如字符**板,字符板[][cols],字符(*板([cols]。甚至投射我的输入板,这会导致其他错误。

如果要将 2D 数组传递给函数,则有一个特殊的语法。不幸的是,前面的其他 2 个答案没有完全正确回答。

可以通过引用或指针传递。数组维度必须是编译时常量。这是C++的要求。

请看:

constexpr size_t NumberOfRows = 3;
constexpr size_t NumberOfColumns = 4;
// Typedef for easier usage
using IntMatrix2d = int[NumberOfRows][NumberOfColumns];
//Solution 1 ------
// Pass by reference
void function1(int(&matrix)[NumberOfRows][NumberOfColumns])  {}
// Pass by pointer
void function2(int(*m)[NumberOfRows][NumberOfColumns])  {}
//Solution 2 ------
// Pass by reference
void function3(IntMatrix2d& matrix) {}
// Pass by pointer 
void function4(IntMatrix2d* matrix) {}

int main()
{
// Solution 1
// Handwritten matrix. Dimension is compile time constant
int matrix1[NumberOfRows][NumberOfColumns];
// Pass by reference
function1(matrix1);
// Pass by pointer
function2(&matrix1);
// Solution 2 -----
IntMatrix2d matrix2;
// Pass by reference
function3(matrix2);
// Pass by pointer
function4(&matrix2);
return 0;
}

如果你对类型定义使用 using ,那么它会变得相当直观。

如果你对指针不是很满意,那么有一些简单的方法可以完成任务

1。默认情况下,在将数组传递给函数之前,您必须定义2D 数组大小,以便函数似乎不知道该大小。

#include <iostream>
const std::size_t rows=5;
const std::size_t cols=5;
void printArray(char board[rows][cols]) {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
std::cout << board[r][c];
std::cout << " ";
}
std::cout << "n";
}
}
int main() {
char board[rows][cols];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
board[r][c] = '0';
}
}
printArray(board);
return 0;
}


2. 使用矢量。让您的电路板成为矢量。

#include <iostream>
#include <vector>
void printArray(std::vector<std::vector<char>> &board) {
for (int r = 0; r < board.size(); r++) {
for (int c = 0; c < board[0].size(); c++) {
std::cout << board[r][c];
std::cout << " ";
}
std::cout << "n";
}
}
int main() {
std::vector<std::vector<char>> board(rows, std::vector<char>(cols, '0'));
printArray(board);
}

我在为一个类做项目时遇到了这个问题。为了解决它,我创建了一个双指针数组,然后将其传递给函数来操作它。

int** createArr(){
int** pixels = 0;
pixels = new int*[numrows];
for (int row = 0; row < numrows; row++){
pixels[row] = new int[numcols];
for (int col = 0; col < numcols; col++){
ss >> pixels[row][col];
}
}
return pixels;
}
int** newArr = createArr(); //calls function to create array
func(newArr); //where func is a function that modifies the array.

不要忘记在最后删除数组以避免内存泄漏。希望这有帮助。