Wednesday, November 15, 2023

Passing Arrays to the Functions

An a Array can be passed to a function using pointers. For this, a function that expects an array can declare that formal parameter in either of thw two ways.

func(int a[ ]);    

or                      

func(int *a);

When we pass the name of the array to a function, the address of the zero element of the array is copied to the local pointer variable in the function.

When a formal parameter is declared in a function header as an array, it is interpreted as a pointer variable and not an array. With this pointer variable you can access all the elements of the array by using the expression, array_name + index.

Example:

#include<iostream.h>

#include<conio.h>

void display(int *arr,int n);

void main()

{

clrscr();

int arr[20],n;

cout<<"\nEnter the size of an Array\n"; cin>>n;

cout<<"\nEnetr the elements into the array\n";

for(int i=0;i<n;i++)

cin>>arr[i];

display(arr[0],n);

getch();

}

void display(int *arr,int n)

{

for(int i=0;i<n;i++) cout<<*(arr+i)<<"\t";

}

0 comments:

Post a Comment

Data Structures with C++



NET/SET/CS PG



Operating Systems



Computer Networks



JAVA



Design and Analysis of Algorithms



Programming in C++

Top