2d array expand()

Hey!
I just coded this little program:

int path [][] = new int[1][4];
//path = {{0,0,0,0}}
          
path [0][0] = -1;
//path = {{-1,0,0,0}}

path = (int[][])expand(path, path.length + 1);
//path = {{-1,0,0,0},  
//         {0,0,0,0}}

println(path.length);
// prints 2

println(path[0].length);
// prints 4

path[1][0] = 1;
//should do:
//path = {{-1,0,0,0},  
//         {1,0,0,0}}

But when I try to run it I get an error at the last line(path[1][0] = 1;).
It says “NullPointerException”. :worried:

Can someone help me? :grinning:

I think, after expand, you need to init the new lines (tell them, they are arrays too)

Sketch

size(330, 330); 

int path [][] = new int[1][4];
//path = {{0,0,0,0}}

path [0][0] = -1;

path [0][2] = -1;
//path = {{-1,0,0,0}}

path = (int[][]) expand (path, path.length + 2);

// I think you need to init the new lines  
for (int i=0; i<path.length; i++)
  path[i] = new int[4];

//path = {{-1,0,0,0},  
//         {0,0,0,0}}

println(path.length);
// prints 2

println(path[0].length);
// prints 4



path[1][0] = 1;
path[1][3] = 2;
path[2][0] = 3;

//should do:
//path = {{-1,0,0,0},  
//         {1,0,0,0}}

int distFromBorder=40;

for (int i=0; i<path.length; i++) {
  for (int i2=0; i2<path[i].length; i2++) {
    text(path[i][i2], i*22+distFromBorder, i2*30+distFromBorder); 
    text("|", i*22+distFromBorder+10, i2*30+distFromBorder);
  }
}
3 Likes