c++ - 无法将二维字符数组传递给函数(C++)
问题描述
我正在尝试将二维字符数组传递给函数,但是 vs code 给了我以下错误消息:
无法将 '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;
}
我正在尝试将二维数组网格传递给函数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 容器。
推荐阅读
- string - 如何在 MATLAB 中从变量名数组创建相同的变量?
- flutter - 无法将扫描流中的条形码扫描传递到列表中
- java - 有没有更有效的方法来编写多个 if else?
- .net - System.Net.Mail.SmtpClient 支持什么版本的 TLS?
- database - 外部服务对于 laravel 中的数据库来说太快了
- symfony - 基于 Symfony 表单中的下拉选择从数据库中获取数据
- google-sheets - 如何从 IMPORTDATA 列表中筛选出错误?
- javascript - 有没有办法在 google-cloud-firestore 中的对象数组中搜索具有特定字段的对象
- visual-studio - UpToDateCheckBuilt 不起作用,并且构建始终有效
- typescript - 使用 TypeScript 中的类型定义对象键的前缀