将2D数组传递给函数

时间:2012-10-21 08:43:04

标签: c++ function parameter-passing multidimensional-array

我已经在多个网站上查看了很多关于如何将2D数组传递到函数中的主题。但由于某些原因,它们似乎都没有正常工作。

#include <stdio.h>
#include <iostream>
#include <string>


void display(char maze[NUM_COLS],int NUM_ROWS);

int findpath(int x, int y);





int main(void)

{
 int NUM_ROWS;
 int NUM_COLS;
 std::cin >> NUM_ROWS >> NUM_COLS;
 std::string w;
 char maze[NUM_ROWS][NUM_COLS];

 getline(std::cin, w);


 for (int row = 0; row < NUM_ROWS; row++)
 {
    for(int col = 0; col < NUM_COLS; col++)
    {
        maze[row][col] = w[col + (row * NUM_COLS)];
    }
 }

 if ( find_path(0, 0) == 1 )
 {
  printf("Success!\n");
 }
 else
 {
  printf("Failed\n");
 }

  display(maze[NUM_COLS],int NUM_ROWS);


    return 0;

}


void display(char maze[NUM_COLS],int NUM_ROWS)
{

    printf("MAZE:\n");

    for ( int i = 0; i < num_rows; i++ )

        printf("%.*s\n", NUM_COLS, maze[i]);

    printf("\n");



    return;

}





int findpath(int x, int y)

{

    // If x,y is outside maze, return false.

    if ( x < 0 || x > NUM_COLS - 1 || y < 0 || y > NUM_ROWS - 1 ) 
    {
     return 0;
    }

    // If x,y is the goal, return 1.

    if ( maze[y][x] == 'G' ) 
    {
     return 1;
    }

    // If x,y is not open, return false.

    if ( maze[y][x] != ' ' && maze[y][x] != 'S' ) 
    {
     return 0;
    }


    // Mark x,y part of solution path.

    maze[y][x] = '+';

    // If find_path North of x,y is 1, return 1.

    if ( find_path(x, y - 1) == 1 ) 
    {
     return 1;
    }

    // If find_path East of x,y is 1, return 1.

    if ( find_path(x + 1, y) == 1 ) 
    {
     return 1;
    }

    // If find_path South of x,y is 1, return 1.

    if ( find_path(x, y + 1) == 1 ) 
    {
     return 1;
    {

    // If find_path West of x,y is 1, return 1.

    if ( find_path(x - 1, y) == 1 ) 
    {
     return 1;
    }

    // Unmark x,y as part of solution path.

    maze[y][x] = 'x';

    return 0;
}

我无法找到任何方法来传递我的2D数组以使一切正常。如果我只是强制在main之外的2D数组,函数是有效的。但是当获取信息并且必须将它们传递给函数时,它会让我声明错误。

void display(char maze[NUM_COLS],int NUM_ROWS);

  display(maze[NUM_COLS],int NUM_ROWS);
这是我的问题。当我编译时,我的错误是它不接受我的数组中的任何部分。我只是不知道传递我的数组的正确方法。代码工作。如果我全局设置一个2D数组,这样我就不必传递任何东西,而且函数只能抓住NUM_COLS和NUM_ROWS以及数组本身,并且乱用它,函数会编译并运行。

1 个答案:

答案 0 :(得分:3)

#include <iostream>
#include <cstdio>

template<typename T, size_t rows, size_t cols>
void display(T (&matrix)[rows][cols])
{
    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()
{
    char maze[3][4] = {
        "asd",
        "123",
        "fgh"
    };
    display<char, 3, 4>(maze);
}