public int[][] getInfo() {
int[][] result = new int[10][20];
return result;
}
public void main() {
int[][] result = getInfo();
System.out.println("结果长度:" + result.length);
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result.length; j++) {
System.out.println(result[i][j]);
}
}
}
上面是一段java的代码,功能就是获取返回的二维数组,并输出二维数组的大小,并遍历数组的内容,前提是我并不知道返回来得数组大小。
如何把它翻译成C语言?其实我就是想理解C语言如何返回二维数组,如何获取数组的大小。
For example, use some black magic (the black magic of C language is of course macro + pointer). Someone has proposed before that the length of an array should be recorded before the first address.
This method has three advantages compared to returning a structure pointer:
The meta-information structure is hidden from the user (a bit like a private field in object-oriented). Here array_length is a macro so it is writable. If it is rewritten as a function, it is read-only
You can use the traditional
[]
operator to directly get the offset without first dereferencing or anything likeAnother thing is that if a structure is returned, it is equivalent to dynamic allocation twice, which makes memory management more troublesome. You only need to
malloc
once here and then release it once.If you are using C++, you don’t need to bother using vector. Just use two template elements to overload arrays of different lengths and you’re done. Remember that parameters are references:
Give me a method. I tested it. If an error is reported, please debug it according to the environment
Since you are writing Java, I can only explain it briefly:
Simple method: C language can modify the value pointed by the function parameter, and the number of rows and columns of the two-dimensional array can be returned through the function parameter.
Second method: Define a structure to store the pointer of the two-dimensional array, the number of rows and the number of columns. getInfo allocates this structure, assigns a value, and returns the pointer of this structure.
C data (no matter how many dimensions) are represented by pointers. A simple pointer cannot describe the length of the data, so at least two pieces of data need to be returned anyway. The problem is that function can only return one piece of data, then, There are two common solutions below
Define a structure to contain two data, such as
Define pointer parameters directly in the function to return
What a complicated feeling!
Write getInfo as a standard function for allocating memory. The main reason is that it takes a little effort when doing pointer casting.
Use vector;
vector<vector<int> > vt;
After the function finally returns vt through the object, you can get the elements of each dimension through .size() in the main function;