Passing 1D Array using Pointer Notation in C
Notes:
Passing Array (1D) to Function in C using Pointer notation:
Passing 1D ( one dimensional ) array to function in C:
W.K.T. an array name represents address of the first element in the array. So, whenever we pass an array to a function, address of the first element in the array is passed.
W.K.T. while calling a function; if we pass address of a memory location; then it is called as pass by reference or call by reference.
There are 2 different notations for passing an array to a function:
1. Array notation : [ ]
- basic syntax of declaring a function; for accepting 1D array using array notation
return_type functionName(datatype paramName[ ]);
Ex:
void display(int arr[ ],int arraySize);
2. Pointer notation : *
- basic syntax of declaring a function; for accepting 1D array using pointer notation
return_type functionName(datatype *paramName);
Ex:
void display(int *arr,int arraySize);
Note: While passing an array to a function; it is also recommended to pass its size
Example Code: Passing 1D array to function using pointer notation
#include <stdio.h>
void display(int *arr,int size);
int main()
{
int arr1[5] = {1,2,3,4,5};
display(arr1,5);
return 0;
}
void display(int *arr,int size)
{
int i=0;
for(i=0; i<size; i++)
{
printf("%d\n",*(arr+i));
}
}