c + +:通过引用传递2d数组?

时间:2020-03-18 17:50:51

标签: c++ arrays pointers parameter-passing

我又回到了c ++,并且在弄清楚如何将2D数组传递给函数时遇到了麻烦。下面的代码是我当前的尝试,我已经能够使用以下方式通过引用传递矢量字符串:

vector<string> g_dictionary;
getDictionaryFromFile(g_dictionary, "d.txt");
...
void getDictionaryFromFile(vector<string> &g_dictionary, string fileName){..}

但是,当我尝试对2d数组执行相同的操作时,如下所示,在“ solve_point(boardEx);”行中出现错误表示char&类型的引用不能用boardEx [5] [4]类型的值初始化

#include <stdio.h>   
#include <string>
using namespace std;

void solve_point(char* &board){ 
    printf("solve_point\n");
    //board[2][2] = 'c';
}

int main(){
    char boardEx[5][4];
    solve_point(boardEx);
}

3 个答案:

答案 0 :(得分:2)

类型char*&是对指针的引用。 “ 2d”数组会衰减为指向数组的指针。

对于数组boardEx,它将衰减为类型char(*)[4],该类型必须是您的函数接受的类型:

void solve_point(char (*board)[4]) { ... }

或者您可以使用模板来推导数组尺寸

template<size_t M, size_t N>
void solve_point(char (&board)[M][N]) { ... }

或使用std::array

std::array<std::array<char, 5>, 4> boardEx;

...

void solve_point(std::array<std::array<char, 5>, 4> const& board) { ... }

或使用std::vector

std::vector<std::vector<char>> boardEx(5, std::vector<char>(4));

...

void solve_point(std::vector<std::vector<char> const& board) { ... }

考虑到问题的编辑,使用std::vector的解决方案是唯一可能的便携式标准解决方案。

答案 1 :(得分:0)

可以使用以下方法定义对2D数组的引用:

char (&ref)[5][4] = boardEx;

您可以将函数更改为使用相同的语法。

void solve_point(char (&board)[5][4]){ 
    printf("solve_point\n");
    //board[2][2] = 'c';
}

对于动态分配的数组,最好使用std::vector

int width = 7;
int height = 9;
char boardEx[width][height];
一些编译器支持

作为扩展,但它不是标准的C ++。而是使用:

int width = 7;
int height = 9;
std::vecotr<std::vector<char>> boardEx(width, std::vector(height));

相应地更新solve_point

答案 2 :(得分:0)

您可以声明通过值或引用接受数组的函数。

例如(按值)

void solve_point( char ( *board )[4] ){ 
    printf("solve_point\n");
    //board[2][2] = 'c';
}

int main(){
    char boardEx[5][4];
    solve_point(boardEx);
}

或(通过引用)

void solve_point(char ( &board )[5][4] ){ 
    printf("solve_point\n");
    //board[2][2] = 'c';
}

int main(){
    char boardEx[5][4];
    solve_point(boardEx);
}

在两种情况下,您都可以使用这样的表达式访问数组的元素

board[i][j] = 'c';

请记住,如果您有一个像这样的多维数组

T a[N1][N2][N3];

其中T是某种类型说明符,那么您可以按照以下方式重写声明

T ( a[N1] )[N2][N3];

现在要获取指向数组元素的指针,只需将( a[N1] )替换为( *pa )

T ( *pa )[N2][N3] = a;

要获取对数组的引用,请像这样重写其声明

T ( a )[N1][N2][N3];

并用( a )代替( &ra ),例如

T ( &ra )[N1][N2][N3] = a;

如果要编写一个通过引用接受不同大小的二维数组的函数,则可以编写

template <typename T, size_t M, size_t N>
void solve_point( T ( &board )[M][N] ){ 
    //...
}

int main(){
    char boardEx[5][4];
    solve_point(boardEx);
}
相关问题