Pass arrays to functions in c programming; Through this tutorial, you will learn how to pass single and multidimensional arrays to a function in C programming with the help of examples.
Pass Arrays to Function in C
There are two possible ways to pass array to function; as follow:
- Passing array to function using call by value method
- Passing array to function using call by reference
- FAQ’s pass array to function in c
- Passing a Multi-dimensional array to a function
Passing array to function using call by value method
To pass the value of an array while calling a function; this is called function call by value. See the example for passing an array to function using call by value; as follow:
#include<stdio.h>
void disArray(int a);
int main()
{
int myArray[] = { 2, 3, 4, 5, 6 };
disArray(myArray[3]); //Passing array element myArray[2] only.
return 0;
}
void disArray(int a)
{
printf("%d", a);
}
Passing array to function using call by reference
To pass the address of an array while calling a function; this is called function call by reference. See the example for passing an array to function using call by reference; as follow:
#include<stdio.h>
void disArray(int *a)
{
printf("The memory location of array is:- %d", a);
}
int main()
{
int myArray[] = { 2, 3, 4, 5, 6 };
disArray(&myArray[3]); //Passing array element myArray[2] only.
return 0;
}
FAQ’s pass array to function in c
Passing a Multi-dimensional array to a function
You can see the following example to pass a multidimensional array to function as an argument in c programming; as follow:
#include<stdio.h>
void disArray(int arr[3][3]);
int main()
{
int arr[3][3], i, j;
printf("Please enter 9 numbers for the array: \n");
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 3; ++j)
{
scanf("%d", &arr[i][j]);
}
}
// passing the array as argument
disArray(arr);
return 0;
}
void disArray(int arr[3][3])
{
int i, j;
printf("The complete array is: \n");
for (i = 0; i < 3; ++i)
{
// getting cursor to new line
printf("\n");
for (j = 0; j < 3; ++j)
{
// \t is used to provide tab space
printf("%d\t", arr[i][j]);
}
}
}