Comment
Author: Admin | 2025-04-28
Know how to pass arrays to function. We can pass arrays to functions as an argument same as we pass variables to functions but we know that the array name is treated as a pointer using this concept we can pass the array to functions as an argument and then access all elements of that array using pointer.So ultimately, arrays are always passed as pointers to the function. Let’s see 3 ways to pass an array to a function that are majorly used.1. Passing Array as a PointerIn this method, we simply pass the array name in function call which means we pass the address to the first element of the array. In this method, we can modify the array elements within the function.Syntaxreturn_type function_name ( data_type *array_name ) { // set of statements}2. Passing Array as an Unsized ArrayIn this method, the function accepts the array using a simple array declaration with no size as an argument.Syntaxreturn_type function_name ( data_type array_name[] ) { // set of statements}3. Passing Array as a Sized ArrayIn this method, the function accepts the array using a simple array declaration with size as an argument. We use this method by sizing an array just to indicate the size of an array.Syntaxreturn_type function_name(data_type array_name[size_of_array]){ // set of statements}Note: Array will be treated as a pointer in the passed function no matter what method we use. As the array are passed as pointers, they will loose the information about its size leading to a phenomenon named as Array Decay.Example: Illustrating Different Ways to Pass Arrays to a Function C++ #include using namespace std;// passing array as a sized array argumentvoid printArraySized(int arr[3], int n){ cout "Array as Sized Array Argument: "; for (int i = 0; i n; i++) { cout arr[i] " "; } cout endl;}// passing array as an unsized array argumentvoid printArrayUnsized(int arr[], int n){ cout "Array as Unsized Array Argument: "; for (int i = 0; i n; i++) { cout *(arr + i) " "; } cout endl;}// Passing array as a pointer argumentvoid printArrayPointer(int* ptr, int n){ // Print array elements using pointer ptr // that store the address of array passed cout "Array as Pointer Argument: "; for (int i = 0; i n; i++) { cout ptr[i] " "; }}// driver codeint main(){ int arr[] = { 10, 20, 30 }; // Call function printArray and pass //
Add Comment