Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Metal Typhoon

Making a multidimensional array in java

This topic is 5270 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

i know that the following way can be used to do a multidimensional array ... public class Foo { int arr[][] = new int [8][8]; public void Test () {arr[0][0] = 1;} } but i''m running into problems. My problem is the following : i''m doing a private class inside Foo ,that would be like a struct in c++ , and trying to make a multidim array out of it.. but when i compile and try to access the array it says null pointer.. code below public class Foo { private class Foo2 { public int row = 0; public int col = 0; } public void Test () { Foo2 arr[][] = new Foo2 [8][8]; arr[0][0].row = 1; //<-- Null ?? } } but if i do a NON array variable it works just fine... can someone explain what i''m doing wrong here ?

Share this post


Link to post
Share on other sites
Advertisement
Yep - when you create an array of reference types (i.e. objects), you need to specifically create an object for each element of the array. For instance:


// This is correct as it tells Java to make room for our objects

Foo2 arr[][] = new Foo2 [8][8];

// We need to loop through to create a new object for each element

for ( int i = 0; i < 8; i++ ) {
for ( int j = 0; j < 8; j++ ) {
arr[i][j] = new Foo2;
}
}

arr[0][0].row = 1;


- Nanoprobe

Share this post


Link to post
Share on other sites
Yup. Just remind yourself that every non-primitive data type is like a pointer, so when you make a "new Foo2 [8][8]", then you''re really making an 8x8 array of pointers.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!