2014-10-07 60 views
0

我已經將這條條紋分解爲裸露的骨骼代碼。實際上,我需要將2d數組傳遞給函數,但是在執行時從文本文件中讀取數組的大小。我在這個主題上讀到的所有內容都表明這是實現它的方式,但編譯器另有說明。這裏的代碼:爲什麼在Code :: Blocks中不能用mingw編譯?

#include <iostream> 

using namespace std; 

template <size_t r, size_t c> 
void func(int (&a)[r][c]) 
{ 
    return; 
} 

int main() 
{ 
    int rows = 5; 
    int cols = 6; 
    int Array[rows][cols]; 

    func(Array); 

    return 0; 
} 

我寧願避免載體,因爲我對他們極其陌生。這是編譯器的輸出:

-------------- Build: Debug in test (compiler: GNU GCC Compiler)--------------- 

mingw32-g++.exe -Wall -fexceptions -g -c C:\Users\ME\Desktop\test\test\main.cpp -o obj\Debug\main.o 
C:\Users\ME\Desktop\test\test\main.cpp: In function 'int main()': 
C:\Users\ME\Desktop\test\test\main.cpp:20:15: error: no matching function for call to 'func(int [(((unsigned int)(((int)rows) + -0x000000001)) + 1)][(((unsigned int)(((int)cols) + -0x000000001)) + 1)])' 
C:\Users\ME\Desktop\test\test\main.cpp:20:15: note: candidate is: 
C:\Users\ME\Desktop\test\test\main.cpp:6:25: note: template<unsigned int r, unsigned int c> void func(int (&)[r][c]) 
Process terminated with status 1 (0 minute(s), 0 second(s)) 
1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) 

回答

2

在此代碼

int rows = 5; 
int cols = 6; 
int Array[rows][cols]; 

Array不是一個普通的C++多維數組,但C99 可變長度數組,或VLA。

這不是標準的C++。

而是做

int const rows = 5; 
int const cols = 6; 
int Array[rows][cols]; 

這工作,因爲初始化表達式是在編譯時已知。


爲了避免這樣的問題,選項-pedantic-errors添加到您的G ++調用。

+0

我剛剛使用「rows」和「cols」作爲參數。行數和列數將在運行時從文本文件讀入。這是否仍然有效? – bobsicle0 2014-10-07 04:06:12

+0

@ bobsicle0 nope。在編譯時,從文本文件中讀取的數字是未知的。爲你的存儲使用'std :: vector'。 – 2014-10-07 04:38:32