Java functions can easily return an array, while C/C ++ cannot directly return an array. This is because in C/C ++, arrays are not a type and therefore cannot be directly returned.
In C/C ++, there are two methods to return an array.
Method 1:
Returns a pointer to an array. For example, char (* retArray) [10] declares a function retArray. This function can return an array pointing to 10 char elements.
Example:
[Cpp]
# Include <stdio. h>
# Include <stdlib. h>
Int (* retArray () [10]
{
Int (* a) [10];
Int I = 0;
/* Dynamically open up space */
A = calloc (10, sizeof (int ));
/* Assign a value */
For (I = 0; I <10; I ++)
{
(* A) [I] = I;
}
Return;
}
Int main ()
{
Int (* B) [10];
/* The function returns the pointer to the array */
B = retArray ();
/* Print the first element */
Printf ("% d/n", (* B) [0]);
/* Release space */
Free (B );
Return 0;
}
Method 2:
If you do not like to return an array in the form of a pointer, you can return a structure. This method is relatively safe, so you can avoid Memory leakage caused by forgetting to release pointers,
It can also avoid errors caused by access to the hanging pointer. However, the disadvantage is that the structure is copied first and then returned. If the structure is large, it will affect the efficiency and occupy a large amount of memory.
Example:
[Cpp]
# Include <stdio. h>
Struct tag
{
Int a [10];
} X, y;
Struct tag retArray ()
{
Int I = 0;
For (I = 0; I <10; I ++)
X. a [I] = I;
Return x;
}
Int main ()
{
Struct tag y = retArray ();
Printf ("% d/n", y. a [3]);
Return 0;
}
Note:
(1) When returning pointers, remember to avoid Memory leakage and access to the hanging pointer.
(2) Many people think that pointers are equivalent to arrays, which is wrong. Int (* a) [10] and int B [10] cannot be directly assigned with a = B. When the array and pointer are passed as function parameters, the two can be considered to be equivalent, because the array will be converted to a pointer for transmission.
(3) the method for returning multi-dimensional arrays is similar.
From herbert's knowledge base