We are about to switch to a new forum software. Until then we have removed the registration on this forum.
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
Answers
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
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 be3
this time.Aha. I see. I misunderstood the dimensions in relation to the declarations then. I'm fairly new to this 2D array thing. Thanks!
Indeed the
[]
have 3 diff. meanings:PImage[][]
.new PImage[rows][cols]
.[]
operators for as how deep we go into its dimension(s).Some extra observations:
imgs.length
.[]
operators as the total amount of dimensions:image(imgs[j][i], i*10, j*10); // 2d array element access
[]
+ 1:PImage[] arr2ndDim= imgs[3]; // 1 [] = 2 dimensions deep.
PImage [][] arr1stDim = imgs; // 0 [] = 1 dimension deep. same as outer dimension.
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...
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