2013-07-02 31 views
1

我似乎得到一個OutOfRangeException,指出以下:「索引出表限制」(不準確的翻譯,我的VS是法國人),這是相關代碼:得到不正確的OutOfRange例外

pntrs = new int[Pntrnum]; 
for (int i = 0; i < Pntrnum; i++) 
{ 
    stream.Position = Pntrstrt + i * 0x20; 
    stream.Read(data, 0, data.Length); 
    pntrs[i] = BitConverter.ToInt32(data, 0); 
} 

Strs = new string[Pntrnum]; 
for (int i = 0; i < Pntrnum; i++) 
{ 
    byte[] sttrings = new byte[pntrs[i + 1] - pntrs[i]];//the exception occures here ! 
    stream.Position = pntrs[i]; 
    stream.Read(sttrings, 0, sttrings.Length); 
    Strs[i] = Encoding.GetEncoding("SHIFT-JIS").GetString(sttrings).Split('\0')[0].Replace("[FF00]", "/et").Replace("[FF41]", "t1/").Replace("[FF42]", "t2/").Replace("[FF43]", "t3/").Replace("[FF44]", "t4/").Replace("[FF45]", "t5/").Replace("[FF46]", "t6/").Replace("[FF47]", "t7/").Replace("[0a]", "\n"); 

    ListViewItem item = new ListViewItem(new string[] 
       { 
        i.ToString(), 
        pntrs[i].ToString("X"), 
        Strs[i], 
        Strs[i], 
       }); 
    listView1.Items.AddRange(new ListViewItem[] {item}); 
} 

我做錯了什麼?

+3

問題出在'pntrs [i + 1]'。當pntrs處於最終索引時,您將添加'1',這會將其推出界限。 – keyboardP

+1

'i + 1'將超出'pntrs'的範圍 –

回答

3

你所得到的OutOfRangeException,因爲我在下面的行+ 1:

byte[] sttrings = new byte[pntrs[i + 1] - pntrs[i]]; 

您可以通過以下方式輕鬆防止:

for (int i = 0; i < Pntrnum - 1; i++) 
{ 
    byte[] sttrings = new byte[pntrs[i + 1] - pntrs[i]]; 
    ... 
} 

這將防止i + 1超出範圍。

+0

謝謝你,它的工作:) – Omarrrio

4

C#數組是零索引;也就是說,數組下標從零開始(你的情況,你有一個從0到pntrsPntrnum-1 elemets),所以當i == Pntrnum - 1pntrs[i + 1]試圖在最後一次迭代的pntrs

+0

感謝您向我展示我錯在哪裏:) – Omarrrio

+0

總是樂於幫助) –

+0

但如果我把pntrnum - 1放在'我'上,它不會從文本文件中獲取最後一個字符串。 – Omarrrio

4

邊界之外訪問元素i + 1的問題在9 然後循環 supposse最後一個索引的,它會嘗試獲取10個,問題

+0

謝謝你給我看我在哪裏錯了:) – Omarrrio