use*_*304 0 c c# java multidimensional-array
在Java或C#编程语言中,我们可以声明如下的多维数组:
int[][] arr = new int[2][];
arr[0] = new int[3];
arr[1] = new int[4];
Run Code Online (Sandbox Code Playgroud)
我想知道代码中的内存分配机制,特别是它们与C编程语言之间的区别?
我只能从Java的角度讲,但我相信C#的工作方式大致相同(如果不是这样,有人请纠正我).
声明和分配数组以及在执行的哪个阶段执行的操作之间存在差异.
声明数组类型的变量时,它保存对象的引用.这不会创建数组对象或为其组件分配空间,只是变量本身.但初始化器可以创建一个数组,然后该数组成为变量的初始值.例如:
//only has a variable of firstArray (i.e. doesn't create array,
//therefore array memory not used)
int[] firstArray;
//creates variable secondArray and allocates 4 int
//values to the array
int[] secondArray = { 1, 2, 3, 4 };
Run Code Online (Sandbox Code Playgroud)
参考:(§10.2)JLS
当分配的数组没有特定值时,所有元素都接收数组数据类型的默认值(例如,对于布尔值,它将为false,0表示int,等等)例如:
//Creates an array of 5 Object's which will all
//be null.
Object[] objectArray = new Object[5];
Run Code Online (Sandbox Code Playgroud)
这里也是一些多维数组示例:
//This is allocating an int[] array inside myArray at position [0]
int[][] myArray = { { 1, 2 } };
for (int[] i : myArray)
for (int j : i)
System.out.println(j); //will print 1 then 2;
Run Code Online (Sandbox Code Playgroud)
要使用您的一个示例:
//This is declaring a multi-dimensional array of int with a max length of 2
int[][] arr = new int[2][]; //Only declaration, no memory allocation for array components
arr[0] = new int[] {1, 2}; //Allocating memory
arr[1] = new int[] {3, 4}; //Allocating memory
for(int[] i : arr)
for(int j: i)
System.out.println(j); //Will print 1 then 2 then 3 then 4...
Run Code Online (Sandbox Code Playgroud)