0

I need to create an array for which I do not know the size in advance. I used the following, but it gives an index out of bounds error in my for -loop.

string[] arr = s.Split('\n');
int[] indices = new int[arr.Length];

string[][] new_arr = new string[arr.Length][];

for (int i = 0; i < arr.Length; i++)
{
    if (arr[i].StartsWith("21")) 
    {
        indices[i] = i;
    }
}

indices = indices.Where(val => val != 0).ToArray(); //contains indices of records beginning with 21

for (int i = 0; i < indices.Length - 1; i++)
{

    new_arr[0][i] = arr[i];
} //first n elements

The error is in the second for-loop. It says

Object reference not set to an instance of an object.

But I did instantiate the string at the beginning?

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Richeek Dey
  • 257
  • 2
  • 15

2 Answers2

0

You just need to initialize each of the arrays within the jagged array:

indices = indices.Where(val => val != 0).ToArray(); //contains indices of records beginning with 21

// create second-level array 
new_arr[0] = new string[indices.Length] ;

for (int i = 0; i < indices.Length - 1; i++)
{
    new_arr[0][i] = arr[i];  // why 0 here?
} 
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • So what I am trying to do is to create a new column (column 0) with the first n elements from a 1D array. I do not know the "n" (it is dynamic) hence I can't hard-code it. The 0 is to access the 0th column ( it is [i][0], i typed that by mistake) – Richeek Dey Aug 15 '17 at 14:49
  • Regardless, you need to create each sub-array with a fixed size (or use a list and add elements. I'm not familiar with your process to know what the size of the sub-array should be, though. – D Stanley Aug 15 '17 at 15:07
0

For a 2 dimensional array, you will have to specify the size of the first dimension. As I see your code, it is using what is called the jagged array (array containing array as elements) and not a pure 2 dimensional array.

var array1 = new int[2,10]; // this is a 2 dimensional array
var array2 = new int[2][]; // this is an array of 2 elements where each element is an `int[]`

As you notice, we don't need to specify the size of the inside element int[]

Now you understand the jagged array, you can see that you are not initializing the inside element, but simply accessing it - and since it is null by default, you hit the exception.

for (int i = 0; i < indices.Length - 1; i++)
{
    new_arr[0][i] = arr[i];
} //first n elements

In the code above, you should have new_arr[i][0] = arr[i] and also before that line you need to do new_arr[i] = new int[x] where x is teh size that you want for the inside array.

Vikhram
  • 4,294
  • 1
  • 20
  • 32