2D array too large after initialising

Hi there,

I have a 2D or multidimensional array that I use for storing images. It is initialised like this:

int imgCol = 4; int imgRow = 3; PImage[][] imgs = new PImage[imgRow][imgCol];

But before anything has been added to the array it is too big. Because when I write this immediately after (on setup()):

println("imgs[0].length = "+imgs[0].length+" | imgs[1].length = "+imgs[1].length);

This is what is being written in the console:

imgs[0].length = 4 | imgs[1].length = 4

The length of imgs[0] should be 3, not 4. How come?

Cheers, Massimo

Tagged:

Answers

  • Answer ✓

    The length of imgs[0] should be 3, not 4. How come?

    should it?

    you are defining an array[3][4], 3 rows of 4 columns each

    imgs[0] is the 0th row, which is 4 columns long, hence 4

  • Answer ✓

    You're displaying the length of the array's inner (column) dimension on both accounts:
    imgs[0].length & imgs[1].length. Which is = 4.

    For the outer (row) dimension, just get rid of the [] array access operator:
    imgs.length. Gonna be 3 this time.

  • edited December 2015

    Aha. I see. I misunderstood the dimensions in relation to the declarations then. I'm fairly new to this 2D array thing. Thanks!

  • edited December 2015 Answer ✓

    Indeed the [] have 3 diff. meanings:

    1. When declaring the variable type: PImage[][].
    2. When creating the array: new PImage[rows][cols].
    3. And finally when accessing the array, we use a num of [] operators for as how deep we go into its dimension(s).

    Some extra observations:

    • The array variable itself always refers to the outer most dimension: imgs.length.
    • In order to reach the real stored element, we gotta use as many [] operators as the total amount of dimensions: image(imgs[j][i], i*10, j*10); // 2d array element access
    • If using less than that, we get an array @ dimension = num of [] + 1:
    1. PImage[] arr2ndDim= imgs[3]; // 1 [] = 2 dimensions deep.
    2. PImage [][] arr1stDim = imgs; // 0 [] = 1 dimension deep. same as outer dimension.
    3. PImage img = imgs[2][4]; // 2 [] here reach the stored element itself.
  • Thanks. That cleared it up. I don't know where I got the other interpretation from. Perhaps some wrong remains from back when I played around with old school JavaScript...

  • edited December 2015

    JavaScript arrays got same rules as Java for their dimension [] accesses too. ~O)
    Declaration styles are diff. though... :-\"

  • I know now. Thanks. I just remembered it differently. Thanks again for your help. It cleared up some things, eliminating a nasty bug for me. :-D

Sign In or Register to comment.