1

I have this array:

int[][][] D = new int[N][M][2];

My question is: how can I swap D[N][M][0] and D[N][M][1] (it is NOT swap two elements, but swap whole array). It maybe seems silly, but I cannot imagine how 3-dimensional array organize, so I don't know which is the best method to copy it. Moreover, I don't sure does D[N][M][0] and D[N][M][1] is two block consecutive in memory ? If not, so I should do that:

int[][][] D = new int[2][N][M]

right ?

Thanks :)

6
  • As written D[N][M][0] is an int element, not an array. So you are asking to swap two ints, I believe. Commented Jan 12, 2013 at 19:18
  • @BlackVegetable No.I have noted that copy whole array, not single element. But I don't really know how to write it clearly. Can you fix my post ? Commented Jan 12, 2013 at 19:19
  • As Aleksander Gralak answered, you want to omit the last [0] as it indicates a particular index of that final array. You want D[A][B] to be switched not an element within D[A][B]. Commented Jan 12, 2013 at 19:20
  • No you do not have to copy one by one. Look at my answer. Each element in multidimensional array is just a reference to the array which is one dimension smaller. At the end when you have only one dimension, then you have real values. Commented Jan 12, 2013 at 19:22
  • @AleksanderGralak I think you confused me with another poster. I never proposed switching one by one. In fact, I agree with you. Commented Jan 12, 2013 at 19:23

1 Answer 1

1

D[N][M][0] is just a single int. The whole row is under this reference D[N][M], so to swap rows do this:

int[] tmp = D[N][M];
D[N][M] = D[N][M+1];
D[N][M+1] = tmp;
Sign up to request clarification or add additional context in comments.

1 Comment

Just make sure that M+1 is not out of the bounds of the array. (+1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.