Assign a byte array to a 2 dimensional byte array

laila picture laila · Sep 10, 2015 · Viewed 8.3k times · Source

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....
    }
}

Answer

Mark Shevchenko picture Mark Shevchenko · Sep 10, 2015

[][] 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....
    }
}