Discuss how to pass the address of an array to a function and provide an example. Please do not write a complete programming code, only briefly discuss the process and provide a simple example.
Solution
Passing an array to a funciton is of two types.
1.Passing the array name to the function
2.Passing the address of array name to the function
In both the cases, the function takes the address of the first element of array name.
Array name itself represents the address of starting element the array.
------------------------------------------------------------------------------------------------------------------------------
/**
Test program to illustrate the passing an array to a funciton.
*/
#include<iostream>
using namespace std;
//function header types
void printUsingPointer(int *arrPtr,int SIZE);
void printUsingArray(int arr[],int SIZE);
int main()
{
//constant size
const int SIZE=5;
//an array of type integer and stores values
int arr[5]={2,3,4,5,6};
/**
The function printUsingArray takes the address of the first argument as input argument
to the funciton when calling the function
*/
cout<<\"Printing array using array notation :\"<<endl;
//call function printUsingPointer with array,arr and SIZE
printUsingArray(arr,SIZE);
//create a pointer and assign the address of the starting element of array,arr
int *arrPtr=arr;
cout<<\"\ Printing array using pointer notation :\"<<endl;
//call function printUsingPointer with pointer, arrPtr and SIZE
printUsingPointer(arrPtr,SIZE);
system(\"pause\");
return 0;
}
/**The function printUsingPointer that takes an array pointer(reference value) and size
and print the values using pointer notation where * represents an indirection operator
that returns the value at address of arrPtr+index
*/
void printUsingPointer(int *arrPtr, int size)
{
for(int index=0;index<size;index++)
cout<<*(arrPtr+index)<<\" \";
}
/**The function printUsingArray that takes an array and size
and print the values using array notation, arr[index]
*/
void printUsingArray(int arr[],int size)
{
for(int index=0;index<size;index++)
cout<<arr[index]<<\" \";
}
-------------------------------------------------------------------
sample output:
Printing array using array notation :
2 3 4 5 6
Printing array using pointer notation :
2 3 4 5 6
.