我正在關注關于這個主題的互聯網教程,但我有以下情況:
我有一個具有以下簽名的函式:
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''
問題是什么?為什么不能呼叫函式?
uj5u.com熱心網友回復:
變長陣列不是標準的 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];
}
請注意,由于列數是眾所周知的,因此將其傳遞給函式是沒有意義的。此外,通過參考傳遞行數和列數是沒有意義的。
uj5u.com熱心網友回復:
你真的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];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/342681.html
上一篇:使用js將csv轉換為物件鍵值對
下一篇:在BASH中為一組單詞添加邊框
