0

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';
            }
        }
    }
}
2
  • You could read this article to get into multidimensional arrays a bit: msdn.microsoft.com/en-us/library/2yd9wwz4%28v=vs.71%29.aspx Commented Jul 19, 2012 at 13:14
  • I have already read that, I want dynamic values to be entered, but in this link all the examples are given with the help of preinitialised values for arrays Commented Jul 19, 2012 at 13:16

1 Answer 1

7

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';
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

In my application, N will be entered by user i.e. second and 3rd levels of Array, so how should I tackle this problem?
What problem? You know N at the time you're looping, so by creating the dimensions just before you enter the loop it'll just work won't it? Though if you need an arbitrary length collection you can use List.
Just the same way - you have the value in a variable presumably, just use that when you initialise the next two levels of the array?
N is unknown till runtime, so I cant initialize the array, this is the problem
But at the point where you execute that line of code, you know it. It's the upper limit of your loop. So just use it there...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.