Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly assigning values to a 2D Array?

Tags:

I've never done this before and can't find the answer. This may not be the correct data type to use for this, but I just want to assign an int, then another int without a for loop into a 2D array, the values will actual be returns from another function, but for simplicity I've just used int i and k, this is how I thought you'd do it, but its not:

int contents[][] = new int[2][2];
            contents[0][0] = {int i, int k}
            contents[1][1] = {int i, int k}
            contents[2][2] = {int i, int k}

TIA - feel free to point me in the direction of a better data struct to do this if I'm barking up the wrong tree.

like image 980
James MV Avatar asked Feb 16 '12 19:02

James MV


People also ask

How do you assign a value to a 2D array in Java?

int contents[][] = new int[2][2]; contents[0][0] = 1; contents[1][1] = 2; ... That will let you individual assign values to elements in your 2D array, one at a time.

How do you assign a 2D array in C++?

To declare a 2D array, use the following syntax: type array-Name [ x ][ y ]; The type must be a valid C++ data type. See a 2D array as a table, where x denotes the number of rows while y denotes the number of columns.


1 Answers

The best way is probably to just declare and assign all values at once. As shown here. Java will automatically figure out what size the array is and assign the values to like this.

int contents[][] = { {1, 2} , { 4, 5} };

Alternatively if you need to declare the array first, remember that each contents[0][0] points to a single integer value not an array of two. So to get the same assignment as above you would write:

contents[0][0] = 1;
contents[0][1] = 2;
contents[1][0] = 4;
contents[1][1] = 5;

Finally I should note that 2 by 2 array is index from 0 to 1 not 0 to 2.

Hope that helps.

like image 94
lotu Avatar answered Oct 07 '22 07:10

lotu