Pass 1-D array as parameter in C/C++

1-D Array:

Syntax:

    Datatype array_name [size];

Example:

    int arr[3];

Here, the compiler allocates total 6 or 12 bytes (depends on 32 bit or 64 bit OS Type) of continuous memory locations with single name ‘arr’.

But allows to store three different integer values (each in 2/4 bytes of memory) at a time.

How to pass 1-D as parameter into function:

There are two ways to pass parameters in array:
  1.  A one dimensional array can be easily passed as a pointer
  2.  A one dimensional array can be easily passed through array name
   
1-D array can be easily passed through array name:
  • To pass an entire array to a function, only the name of the array is passed as an argument. 
  • No need to pass [ ] operator.
  • Argument array name represents the memory address of the first element of 1-D Array
Example:

#include<iostream>
using namespace std;

void get(int s[]);  // This is function prototype

void get(int se[])  //This is function definition
{
int i;
for(i=0;i<5;i++)
{
cout<<"\n Enter element \n";
cin>>se[i];
}
cout<<"\n********1st Array********\n";
for(i=0;i<5;i++)
{
cout<<se[i];
}
}


int main()
{
int se[5];
get(se);      // This is function call
}


2. A one dimensional array can be easily passed as a pointer:
  • To pass an entire array to a function, only the name of the array is passed as an argument. 
  • In function definition, we use *operator instead of [ ] operator
  • Argument array name represents the memory address of the first element of 1-D Array

Example:

#include<iostream>
using namespace std;

void get(int se[]);       //This is function prototype

int main()
{
int se[5];
get(se);                   //This is function calling
}

void get(int *se)    // This is function definition
{
int i;
for(i=0;i<5;i++)
{
cout<<"\n Enter element \n";
cin>>se[i];
}
cout<<"\n********1st Array********\n";
for(i=0;i<5;i++)
{
cout<<se[i];
}
}


Post a Comment

0 Comments