How do I create an array of arrays?

edited December 2017 in Questions about Code

What I want to do is create a 2D array whose elements are 1D arrays. So this is what my code is:

color edges[][][]=new color[number_of_img][1][]; for(int n=0;n<number_of_img;n++){ for(int m=0;m<=1;m++){ edges[n][m]=new color[img_height]; } }

However this returns an out of bounds exception. What am I doing wrong, and how do I correct it?

Tagged:

Answers

  • edited December 2017
    final int IMAGES = 10, NUM = 1, IMG_HEIGHT = 10;
    final color[][][] edges = new color[IMAGES][NUM][];
    
    for (final color[][] c : edges)
      for (int i = 0; i < NUM; c[i++] = new color[IMG_HEIGHT]);
    
    exit();
    
  • edited December 2017
    for (final color[][] c : edges)
      for (int i = 0; i < NUM; c[i++] = new color[IMG_HEIGHT]);
    

    Could you explain what exactly these lines do? Because I actually omitted a few lines where I'm using m and n to do other stuff

  • edited December 2017

    ... I actually omitted a few lines...

    We can only guess based on what was posted... :-@

  • I didn't think that the solution would require removing the indices, sorry. However it seems that adding the third dimension in the initial definition works

  • A 2D array of 1D arrays is just a 3D array...

  • This is your actual problem

    m <= 1
    

    Your m loop goes from 0 to 1, two values, but you've only defined it to have space for [1] value

  • There is a tutorial on arrays and one on 2D arrays (grids)

Sign In or Register to comment.