[英]Unable to pass 2D character array to function(C++)
我正在尝试将二维字符数组传递给 function 但是 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;
}
我正在尝试将二维数组网格传递给 function NodeDetect
如果你想将一个普通的旧 C 数组传递给 C++ 中的 function,你有两种可能性。
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;
}
您传递给 function 的是一个衰减的指向 char 数组的指针。
只需更正语法,它就会起作用。
附加提示:
不要在 C++ 中使用普通的 C 样式 arrays。 绝不。 请使用 STL 容器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.