【问题标题】:Unable to pass 2D character array to function(C++)无法将二维字符数组传递给函数(C++)
【发布时间】:2021-05-27 16:56:13
【问题描述】:

我正在尝试将二维字符数组传递给函数,但是 vs 代码给了我以下错误消息:

无法将 'char ()[3]' 转换为 'char ()[10]'gcc

代码如下:

#include<string>
using namespace std;
void NodeDetect(char grid[][3], int height, int width)
{
    cout << "\nThe grid output:\n";
    for(int i = 0; i < height; ++i)
    {
        for(int j = 0; j < width; ++j)
            if(grid[i][j] == '0')
            {
                cout << '\n' <<  i << '\t' << j << ", ";

                if(grid[i][j + 1] == '0' && (j + 1) < width)//right neighbour
                    cout << i << '\t' << (j + 1) << ", ";
                else if(grid[i][j + 1] == '.' || (j + 1) == width)
                    cout << "-1 -1, ";

                if(grid[i + 1][j] == '0' && (i + 1) < height)//bottom neighbour
                    cout << (i + 1) << '\t' << j << ", ";
                else if(grid[i + 1][j] == '.' || (i + 1) == height)
                    cout << "-1 -1";
            }
            cout << '\n';
    }
}
int main()
{
    string line;
    char grid[3][3];
    int height, width;                          //height = rows
    cout << "Enter the height and the width:\t";//width = columns
    cin >> height >> width;
    cout << "\nEnter the strings:\n";
    for(int i = 0; i < height; ++i)//initializing the grid
        cin >> grid[i];

    /*
    cout << "\nThe grid:\n";
    for(int i = 0; i < height; ++i)     //displaying the grid
    {
        for(int j = 0; j < width; ++j)
            cout << grid[i][j] << '\t';
        cout << '\n';
    }
    */
    NodeDetect(grid, height, width);
    return 0;
}

我正在尝试将二维数组 grid 传递给函数 NodeDetect

【问题讨论】:

  • 这 10 个是从哪里来的?
  • 添加#include &lt;iostream&gt;后我无法重现您的编译器错误:ideone.com/5TSDAI
  • @kushagra kartik 在呈现的代码中没有包含 10 个元素的字符数组。提供相关代码。
  • 为什么会有变量:heightwidth,您在评论中描述为 rowscolumns

标签: c++ arrays c++11 visual-studio-code computer-science


【解决方案1】:

如果您想将一个普通的旧 C 数组传递给 C++ 中的函数,您有两种可能性。

Pass by reference
Pass by pointer

看来你想通过引用传递。但是你使用了错误的语法。

请看:

void function1(int(&m)[3][4])   // For passing array by reference
{}
void function2(int(*m)[3][4])   // For passing array by pointer
{}

int main()
{
    int matrix[3][4]; // Define 2 dimensional array

    function1(matrix);  // Call by reference
    function2(&matrix); // Call via pointer 
    return 0;
}

你传递给函数的是一个衰减的指向 char 数组的指针。

只需更正语法即可。

附加提示:

不要在 C++ 中使用纯 C 样式的数组。绝不。请使用 STL 容器。

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 2021-12-15
    • 2015-05-27
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多