![]() |
Return an Array from a Function |
This article will deal with the method of returning an array from a Function.
C/C++ functions cannot return an array as a whole but can return a pointer to that array block. The pointer can access the array just as any normal array variable.
In order for you to do that, you have to change the syntax of the function (through which you want to return the array) from data_type function_name (arguments) to data_type * function_name (arguments), where the data_type should be the data type of the returning array and the function must return the address of the array to a pointer variable, which then can access the array. You can use the returned array in your operations just as you would use any normal array.
Let's look at the following code which achieves the purpose -
The following user-defined functions are created -
- creation(int n) - This function creates a dynamic array of size n (formal parameter) and returns the address of the array. This function takes an integer and returns an array pointer of the specified return type (here 'int', as we are creating an array of integers).
- displayed(data_type variable_name[], int variable_name) - This function receives 2 parameters which are an array pointer (variable_name[]) and size of the array as parameters, and does not return any value. The purpose of this function is to display the elements of the array. The datatype of the variable_name[] should be the same as the array datatype.
- In this program, the user is asked to enter the size of an array, that s/he or they want to create.
- After entering the size of the array, the function creation is called by the main() function by passing the size of the array (n) as a parameter.
- The function creation creates a dynamic array of integers and inserts numbers from 0 to 'n' and returns a pointer to the dynamic array.
- The returned address is stored in a pointer variable (p) of the same data type as the created array (here we have created an array of integers, hence we have set the data type of the pointer to int).
- Next, the function displayed is called by the main() function by passing the pointer p and the size of the array (n). The purpose of the function is to display the elements of the array.
- After executing the displayed function, the control returns back to the main() function, which then asks the user to enter the element that they would like to search in the array.
- The search element(ele) is compared with all the elements of the array, and if the element is present, it prints the same, else it prints otherwise.
Thanks for reading. If you found any errors or have suggestions to improve the article, please mention them in the comments.
0 Comments