0

I want to assign a byte[] to a byte[][] but it gives me the run-time error :

Object reference not set to an instance of an object.

this is my code:

for (int i = 0; i < NumberOfChunks; i++)
{
    byte[][] myFile = new byte[NumberOfChunks][];
    myFile[i][0] = buffer[i]; // IT STOPS HERE AND GIVES ME THE ERROR
    if ((i + 1) == NumberOfChunks)
    {
        do sth....
    }
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
laila
  • 15
  • 1
  • 2
  • 7
  • 2
    [What is a `NullReferenceException` and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Soner Gönül Sep 10 '15 at 12:17

2 Answers2

2

[][] is an array of arrays unlike [,].

So allocating first dimension you'll get just array of null pointers to possible arrays.

Try this:

byte[][] myFile = new byte[NumberOfChunks][];
for (int i = 0; i < NumberOfChunks; i++)
{
    myFile[i] = new byte[NumberOfItems];
    myFile[i][0] = buffer[i]; // IT STOPS HERE AND GIVES ME THE ERROR
    if ((i + 1) == NumberOfChunks)
    {
        do sth....
    }
}
Mark Shevchenko
  • 7,937
  • 1
  • 25
  • 29
  • This is a start, but OP has misused `i` - so the code above is still quite wrong. [Not the point you were making; just saying people should not copy the above blindly.] I recommend having *three* index variables: `iIn` to step through input, `iItem` to step through elements of one output row or chunk, and `iChunk` to step through the chunks. Details left to the reader. :) – ToolmakerSteve Mar 03 '18 at 17:42
1

myFile[i][0] is null because you only allocated the first dimension. At the beginning of your loop, the array looks like this:

myFile -> [null, null, null, ...]

You can allocated the other dimension by iterating over your array:

byte[][] myFile = new byte[NumberOfChunks][];
for (int i = 0; i < NumberOfChunks; ++i)
{
    myFile[i] = new byte[NumberOfChunks];
}

The result will be:

myFile -> [byte[], byte[], byte[] ...]

So myFile[i] will be pointing to one of the byte[] instead of a null reference.

As a side note, you can use a 2d-array byte[,] in order to allocate the two dimensions at the same time. Just be aware that the performances are not equivalent.

Vincent
  • 666
  • 7
  • 21