简体   繁体   English

在C#数组中未处理NullReferenceException

[英]NullReferenceException was unhandled in c# array

I am getting the error - NullReferenceException was unhandled, in the following code. 我收到错误-在以下代码中未处理NullReferenceException。 I want to extract characters from string pt. 我想从字符串pt中提取字符。 However I am getting correct value outside the for loops, but not the same inside it. 但是我在for循环之外获得了正确的值,但在循环内部却不一样。

ArrayList list = read();
int N = Values.N;
string pt = Values.PlainText;
MessageBox.Show(""+pt.Length+" "+pt[0]);
int count = 0;
char[][][] array = new char[6][][];
for(int i=0;i<6;i++)
{
    for(int j=0;j<N;j++)
    {
        for(int k=0;k<N;k++)
        {
            if (count < pt.Length)
            {
                array[i][j][k] = 'r';
                //array[i][j][k] = pt[count];
                //count++;
            }
            else
            {
                array[i][j][k] = 'x';
            }
        }
    }
}

You have to initialise the second and third levels of the arrays, you can't just assign elements. 您必须初始化数组的第二层和第三层,不能仅仅分配元素。 So: 所以:

ArrayList list = read();
int N = Values.N;
string pt = Values.PlainText;
MessageBox.Show(""+pt.Length+" "+pt[0]);
int count = 0;
char[][][] array = new char[6][][];
for(int i=0;i<6;i++)
{
    for(int j=0;j<N;j++)
    {
        array[i] = new char[N][]; // <---- Note
        for(int k=0;k<N;k++)
        {
            array[i][j] = new char[N]; // <---- Note
            if (count < pt.Length)
            {
                array[i][j][k] = 'r';
                //array[i][j][k] = pt[count];
                //count++;
            }
            else
            {
                array[i][j][k] = 'x';
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM