0% found this document useful (0 votes)
15 views

Pass Array To Functions in C

Uploaded by

rachealmwubaha8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Pass Array To Functions in C

Uploaded by

rachealmwubaha8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Pass Array to Functions in C++

In C++, a collection of elements stored in contiguous memory locations and having the same
data type is called an array. Passing arrays to functions is done to perform various operations
on array elements without messing up with the main code.
In C++, an array can be passed in a function using a pointer or reference. Understanding the
different approaches to pass arrays is important for writing code according to the needs.
Methods to Pass Array to a Function in C++
In C++, we have the following ways to pass an array as a parameter to the function:
1. As a sized array
2. As an unsized array
3. As a Pointer

Passing as an sized Array


In this method, we pass the array in the same way we declare it with the array type,
name, and size. As we can see, we still have to pass the size of the array as another
parameter because at the end, the array will be treated as a pointer in the function.
Syntax
return_type function_name (datatype array_name [size], int size)
2. Passing as an Unsized Array
This method is similar to the previous method, but the difference is that we dont specify the
size of the array.
Syntax
return_type function_name (data_type array_name[])
Example
The below example demonstrates the passing of array as unsized array.

3. Passing Array as a Pointer


In this method, we pass the memory address of the first element of the array. This method
also allows for dynamic array sizes.
Syntax
return_type function_name (datatype *array_name)
Example
The below example demonstrates how to pass array as a pointer to function.

You might also like