c# - 为什么这个 int 数组会抛出 IndexOutOfRangeException?

标签 c# arrays visual-studio-2010

我觉得问这个问题就像个白痴,但我一生都无法弄清楚为什么会发生这个 IndexOutOfRangeException 。 (我的意思是,我知道为什么发生这种情况,我只是不知道我的代码中有哪些内容无效)检查下面的代码以了解抛出错误的位置:

public int[, ,] FindTablePairings(System.Text.RegularExpressions.MatchCollection mcBegin, System.Text.RegularExpressions.MatchCollection mcEnd)
    {
        int[,,] intTablePairs = new int[mcBegin.Count, 1, 1];
        int[] intBegin = new int[mcBegin.Count];
        int[] intEnd = new int[mcBegin.Count];

        for (int q = 0; q < mcBegin.Count; q++)
        {
            intBegin[q] = mcBegin[q].Index;
        }
        for (int q = 0; q < mcEnd.Count; q++)
        {
            intEnd[q] = mcEnd[q].Index;
        }

        int intBeginCount = mcBegin.Count;
        int intEndCount = mcEnd.Count;
        int i = 0;
        int j = 0;
        int k = 0;

        while (i < intBeginCount)
        {
            j = i;
            while (j < intEndCount)
            {
                if (intBegin[i + 1] < intEnd[j])
                {
                    j++;
                }
                else
                {
                    intTablePairs[i, 0, 0] = intBegin[i];
                    intTablePairs[i, 1, 0] = intEnd[j];
                    intEnd[j] = -1;                         //EXCEPTION OCCURS HERE
                    break;
                }
            }
            if (j == intEndCount)
            {
                intTablePairs[i, 0, 0] = intBegin[i];
                intTablePairs[i, 1, 0] = intEnd[j - 1];
                intEndCount--;
            }

            while (k < intEndCount)
            {
                if (intEnd[k] == -1)
                {
                    k++;
                }
                else
                {
                    intTablePairs[i,0,0] = intBegin[i];
                    intTablePairs[i,1,0] = intEnd[k];
                    intEnd[k] = -1;
                    k=0;
                    break;
                }
            }
        }

        return intTablePairs;
    }

代码只是查看开始标签和结束标 checkout 现的字符索引。没有什么 super 复杂的...但最糟糕的部分是在 intEnd[j] = -1; 处抛出异常,并且在调试器中,在执行该语句之前,所有数组和 MatchCollections 都被抛出正确初始化和填充,包括 intEnd[]!我已进行调试以确保数组存在并已初始化,并且我还清理了解决方案并重建了它。

有人对这里发生的事情有什么建议吗?

最佳答案

我相信错误实际上是在这一行

intTablePairs[i, 1, 0] = intEnd[j];

这里的问题是您在 intTablePairs 上将最后 2 个维度的长度定义为 1。因此,使用索引 1 是无效的,因为它等于长度。看来您打算将边界定义为

int[,,] intTablePairs = new int[mcBegin.Count, 2, 2];

关于c# - 为什么这个 int 数组会抛出 IndexOutOfRangeException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7839856/

相关文章:

javascript - 5x5 网格中所有可能的移动?

java - 是否有一种 "faster"方法可以遍历二维数组而不是使用嵌套 for 循环?

visual-studio-2010 - 您可以将生成的文件包含到 WiX 项目中而不将其添加为现有文件吗

c# - Visual Studio 2010 专业版 : class diagram tool

c# - 如何在 AngularJS 中使用 ng-class 设置边框颜色?

c# - 为所有可能的数字生成一个 Random Int32

c# - 覆盖 Equals() 但不检查所有字段 - 会发生什么?

c# - 如何使用 F# 处理来自 C# 的列表

java - 数组未捕获第一个用户条目

c++ - 错误 LNK2001 : unresolved external symbol Visual C++