Passing an Array to a Function in C++

 Passing an Array to a Function 

Introduction

·       Arrays can be passed to functions as arguments — just like variables.

·       Arrays are always passed by reference, not by value.

·       The function receives the address of the first element.

·       Any changes made inside the function affect the original array.


Usability of Pass Arrays to Functions

  • Perform operations on array elements (e.g., find sum, max, sort, etc.)
  • Avoid copying large amounts of data.
  • Modularize code — make functions reusable for different array inputs.

Syntax:

There are 3 main methods to pass arrays to functions in C++.


Method 1: Using Array Name

Syntax:

void functionName(Type array[]) {

    // Same as Type* array

}

 

Example:-

void display(int arr[], int size) {

    for (int i = 0; i < size; i++) {

        cout << arr[i] << " ";

    }

}

 

int main() {

    int numbers[5] = {10, 20, 30, 40, 50};

    display(numbers, 5);  // Passing array to function

    return 0;

}


 

Method 2: Using Pointer Notation

Syntax:

void functionName(Type* array) {

    // Access elements using pointer arithmetic or array indexing

}

 

Example:-

void display(int *arr, int size) {

    for (int i = 0; i < size; i++) {

        cout << *(arr + i) << " ";

    }

}

 

int main() {

    int numbers[5] = {10, 20, 30, 40, 50};

    display(numbers, 5);

    return 0;

}


 

Method 3: Using a Sized Array in a Parameter

void display(int arr[5]) {

    for (int i = 0; i < 5; i++) {

        cout << arr[i] << " ";

    }

}

 

int main() {

    int numbers[5] = {10, 20, 30, 40, 50};

    display(numbers);

    return 0;

}


 

Passing Multidimensional Arrays

Multidimensional arrays (e.g., 2D arrays) can also be passed to functions, but you must specify the size of all dimensions except the first.

Syntax:

void functionName(Type array[][COLS], int rows) {

    // Access elements using array[i][j]

}

 

Example (2D Array):

#include <iostream>

void print2DArray(int arr[][3], int rows) {

    for (int i = 0; i < rows; ++i) {

        for (int j = 0; j < 3; ++j) {

            std::cout << arr[i][j] << " ";

        }

        std::cout << std::endl;

    }

}

 

int main() {

    int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};

    print2DArray(arr, 2);

    return 0;

}


Example:-  Passing 2D Array to Function

 

void display(int arr[2][3]) {

    for (int i = 0; i < 2; i++) {

        for (int j = 0; j < 3; j++) {

            cout << arr[i][j] << " ";

        }

        cout << endl;

    }

}

 

int main() {

    int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};

    display(matrix);

    return 0;

}

----------------------------------------------------------------------------------------------------------

 

Post a Comment

0 Comments