2016-01-22 104 views
0

我需要製作二維數組,但問題是我需要使用字符串大小作爲數組的大小。到目前爲止,我做到了這一點,但我不斷收到錯誤「表達式必須有一個常數值」。我的程序需要從txt文件讀取一個字符串,然後使用字符串長度/大小來表示二維數組大小。例如:我在txt文件中寫了「hello」,其長度是5.現在我需要使用這個長度並將其存儲爲變量N,並將其用作二維數組的維數。 如何爲這個例子做傢伙?如何將非consant值分配給C++中的二維數組大小?

int main() 
{ 
    string s; 
    ifstream myfile("palindrome.txt", ios::out);  //reading my txt file 

    if (myfile.is_open()) 
     { 
      getline(myfile, s); //storing string in variable s 
     } 
    myfile.close(); 

    int l = s.size(); //reading size of string and storing to variable l 
    const int N = l; 
    int* R= new int[2][N + 1]; 
+0

什麼是錯誤信息? – Phorce

+0

錯誤\t C2540 \t與數組綁定的非常量表達式 – darius

+0

如果要爲具有一個新數組的數組分配內存,則第二個大小必須是常量。在你的情況下,我認爲你應該聲明一個數組(或向量)的字符串。 –

回答

0

這是怎麼回事?

const int N = l; 

int** R = new int*[2]; 

for(int i = 0; (i < 2); i++) 
{ 
    R[i] = new int[N + 1]; 
} 

循環兩次,因爲這是您將行設置爲第一次初始化。您需要在堆上分配內存,但請記住,一旦完成,您將需要釋放內存。這可以通過:

for(int i = 0; (i < 2); i++) 
    delete[] R[i]; 
delete[] R; 
+0

非常感謝你,現在有效:D – darius

相關問題