2013-07-14 65 views
2

我得到錯誤:表達式必須有一個常數值。有沒有一種方法可以真正使用變量,因爲我的行可能會隨着每個將被讀取的文件而改變。C++如何在創建指針時使用變量作爲指針的大小?

Image readFile(string fileName) { 
ifstream file; 
file.open(fileName); 
int row; 
int column; 
Image image(0, 0); 
if(file.is_open()){ 

     file >> row; 
     file >> column; 

} 
int **row[row]; // error right here!!!!!!!!!!!!!!!!!!!!!!!!! ERROR:EXPRESSION MUST HAVE A CONSTANT VALUE 
file.close(); 
image(row, column); 
return image(row, column); 

}

回答

2

你應該動態分配內存,用下面的行替換行

int **row = new int*[rowCount]; 
+1

你還需要確保你使用「刪除」在某些時候處置的內存。 –

+0

太棒了,非常感謝! – user2580974

+1

這是一個非常糟糕的建議,因爲存在'std :: vector'(即使面對異常也要照顧'delete')。 –

4

如果我可以給你一個忠告:不要在此使用原始內存情況。堅持RAII,並使用容器2d數據。

std::vector<std::vector<int>> data; 

如果你以某種方式關心性能看看這個答案,爲什麼使用,而不是連續的存儲:Why is dynamic 2 dimensional data storage (pointer-to-pointer or vector-of-vector) "bad" for simple 2d storage

手冊原始內存的處理很可能導致像內存泄漏,不確定bahaviour等錯誤

+0

確實;至少,一個智能指針可以解決如何釋放內存塊的問題。 –