简体   繁体   中英

NullReferenceException was unhandled in c# array

I am getting the error - NullReferenceException was unhandled, in the following code. I want to extract characters from string pt. However I am getting correct value outside the for loops, but not the same inside it.

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';
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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