简体   繁体   English

无法将二维数组传递给 C++ 中的辅助函数

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

I was learning c++ and implementing the game of life when I created a helper function to print the current board which is a 2d array.当我创建一个辅助函数来打印当前的二维数组时,我正在学习 C++ 并实现生命游戏。 I cannot seem to pass the array into the function as I get an error, "Candidate function not viable: no known conversion from 'char [rows][cols]' to 'char (*)[cols]' for 3rd argument."我似乎无法将数组传递到函数中,因为出现错误“候选函数不可行:第三个参数没有从 'char [rows][cols]' 到 'char (*)[cols]' 的已知转换。” I am using Xcode as an ide if that helps.如果有帮助,我将使用 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;
}

I've tried switching up the parameter to different things such as char **board, char board[][cols], char (*board)[cols].我尝试将参数切换为不同的内容,例如 char **board、char board[][cols]、char (*board)[cols]。 Even casting my input board which leads to other errors.甚至铸造我的输入板,这会导致其他错误。

If you want to pass 2d arrays to a function there is a special syntax.如果要将二维数组传递给函数,则有一种特殊的语法。 Unfortunately, the other previous 2 answers do not answer fully correctly.不幸的是,其他前 2 个答案没有完全正确回答。

You can pass by reference or by pointer.您可以通过引用或指针传递。 The array dimensions must be compile time constants.数组维度必须是编译时常量。 That is a requirement from C++.这是 C++ 的要求。

Please see:请参见:

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;
}

If you typedef or use using for your type definition, then it gets rather intuitive.如果您 typedef 或使用 using 用于您的类型定义,那么它会变得相当直观。

If you are not very comfortable with pointers then there are some easy ways to do the task如果您对指针不是很满意,那么有一些简单的方法可以完成任务

1. You have to define the 2d array size by default , before passing array to the function so that the size doesn't seem to be unknown to the function. 1. 在将数组传递给函数之前,您必须默认定义二维数组大小,以便函数似乎不知道大小。

#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. Use vector . 2. 使用向量 Make your board a vector.使您的电路板成为矢量。

#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);
}

I encountered this problem while doing a project for a class.我在为一个班级做项目时遇到了这个问题。 To work around it, I made a double pointer array, and then used passed it to the function to manipulate it.为了解决这个问题,我创建了一个双指针数组,然后使用将它传递给函数来操作它。

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.

Don't forget to delete your arrays at the end to avoid memory leaks.最后不要忘记删除数组以避免内存泄漏。 Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM