Open In App

How to Pass an Array Pointer as a Function Argument in C++?

Last Updated : 06 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a common situation arises where we have to pass an array to a function to perform some processing. This can be done by passing an array pointer as a function argument.

In this article, we will learn how to pass an array pointer as a function argument in C++.

Passing Array Pointer to Function in C++

For passing an array to a function, we can simply pass the array pointer (that stores the memory address of the first element) along with the size of an array to the function as an argument.

This approach can also be used for dynamic arrays because when we pass an array as a parameter to a function it decays into a pointer to the first element of the array and we will lose the information about its size.

C++ Program for Passing Array Pointer to Function

The below example demonstrates the passing of an array pointer as a function argument.

C++




// C++ program to pass an array pointer as a function
// argument.
#include <iostream>
using namespace std;
  
// Function to print array elements
void printArray(int* arr, int size)
{
  
    for (int i = 0; i < size; ++i) {
        cout << arr[i] << " ";
    }
}
  
int main()
{
    int numbers[] = { 1, 2, 3, 4, 5 };
    int size = sizeof(numbers) / sizeof(numbers[0]);
  
    // Passing array pointer to the function
    printArray(numbers, size);
  
    return 0;
}


Output

1 2 3 4 5 

Explanation: In the above example numbers array is created and it is passed as an array pointer along with its size to a function named printArray()that prints all the array elements.

Note: In C++, by default when passing the entire array to a function, pointer to its first element is passed.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads