微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法将二维字符数组传递给函数C++

如何解决无法将二维字符数组传递给函数C++

我正在尝试将二维字符数组传递给函数,但是 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

解决方法

如果您想将一个普通的旧 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;
}

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

只需更正语法即可。

额外提示:

不要在 C++ 中使用普通的 C 风格数组。绝不。请使用 STL 容器。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。