+ 3

Array in functions

how do i create a function which gets 2 arrays as parameters and returns one array back ? All arrays as Integer. with declaration and so on. thank you !

15th Dec 2017, 12:06 AM
ozan
ozan - avatar
2 Réponses
+ 13
There are two ways to pass an array into a function. Consider the following: void func_arr(int* arr1, int* arr2) { ... } and void func_arr(int arr1[], int arr2[]) { ...} int main() { // ... func_arr (array, array2); } Why does it seem like the first code sample receives pointers as its parameters? You can have a read on array decaying here. https://stackoverflow.com/questions/1461432/what-is-array-decaying The idea is that arrays 'decay' to pointers when they are passed to functions. As for returning an array from a function, there should be no need to do so by altering the return type of a function to return an array. - The first reason is because arrays decay to pointers, and these pointers which contain the address pointing to the first element of the array, are *passed by value* into the function. While changes done to the pointer itself will not reflect outside the function, the array elements which are altered by accessing the pointer will be changed. This makes it feel as if arrays are, by default, passed by reference to functions, and hence the array need not be returned back by the function to the caller. - The second reason is that C++ functions can't return C-style arrays by value. The closest thing you can get is to return a pointer. E.g. int* ret_arr(int arr1[], int arr2[]) { return arr1; }
15th Dec 2017, 1:24 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
thank you for that great answer !
15th Dec 2017, 8:44 AM
ozan
ozan - avatar