无法将2D字符数组传递给函数(c++)



我试图通过一个2-D字符数组函数,但vs代码给了我以下错误信息:

不能转换的字符() [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;
}

我试图传递二维数组网格函数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;
}

传递给函数的是指向char类型数组的衰变指针。

只要改正语法就可以了。

额外的提示:

不要在c++中使用普通的C风格数组。从来没有。请使用STL容器

最新更新