[英]Cant's pass a 2D array to a function in C++
我正在关注关于这个主题的互联网教程,但我有以下情况:
我有一个具有以下签名的函数:
void func(long& rows, long& columns, int array[][columns]);
我正在尝试使用这样的功能:
int matrix[5][4] = {0, -1, 2, -3,
4, -5, 6, -7,
8, -9, 10, -11,
12, -13, 14, -15,
16, -17, 18, -19};
long rows = 5;
long columns = 4;
func(rows, columns, matrix);
^--- 'No matching function for call to 'func''
问题是什么? 为什么不能调用函数?
变长数组不是标准的 C++ 特性。
您可以通过以下方式声明函数和数组
const size_t columns = 4;
void func( size_t rows, const int array[][columns]);
//...
int matrix[][columns] = { { 0, -1, 2, -3 },
{ 4, -5, 6, -7 },
{ 8, -9, 10, -11 },
{ 12, -13, 14, -15 },
{ 16, -17, 18, -19 } };
func( sizeof( matrix ) / sizeof( *matrix ), matrix);
//...
void func( size_t rows, const int array[][columns] )
{
std::cout << rows << columns << array[0][1];
}
请注意,由于列数是众所周知的,因此将其传递给函数是没有意义的。 此外,通过引用传递行数和列数是没有意义的。
你真的在你的程序中定义了func
吗? 以下源代码编译并为我工作正常
#include <iostream>
#define ROW 5
#define COLUMN 4
void func(long &rows, long &columns, int array[][COLUMN]);
int main()
{
int matrix[ROW][COLUMN] = {0, -1, 2, -3,
4, -5, 6, -7,
8, -9, 10, -11,
12, -13, 14, -15,
16, -17, 18, -19};
long rows = 5;
long columns = 4;
func(rows, columns, matrix);
return 0;
}
void func(long &rows, long &columns, int array[][COLUMN])
{
std::cout << rows << columns << array[0][1];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.