You are on page 1of 7

ARRAY TO FUNCTIONS

How Arrays are Passed to Functions in


C?
• A whole array cannot be passed as an argument to a function in
C++. You can, however, pass a pointer to an array without an
index by specifying the array’s name.

• In C, when we pass an array to a function say fun(), it is always


treated as a pointer by fun(). The below example demonstrates
the same.
#include <stdio.h>
#include <stdlib.h>
// Note that arr[] for fun is just a pointer even if square
// brackets are used
void fun(int arr[]) // SAME AS void fun(int *arr)
{
unsigned int n = sizeof(arr)/sizeof(arr[0]);
printf("\nArray size inside fun() is %d", n);
} Output
Array size inside main() is 8
// Driver program
int main() Array size inside fun() is 2
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
unsigned int n = sizeof(arr)/sizeof(arr[0]);
printf("Array size inside main() is %d", n);
fun(arr);
return 0;
}
#include <stdio.h>

void fun(int *arr, unsigned int n)


{
int i;
for (i=0; i<n; i++)
Output
printf("%d ", arr[i]);
12345678
}

// Driver program
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
unsigned int n = sizeof(arr)/sizeof(arr[0]);
fun(arr, n);
return 0;
}
Pass Multidimensional Arrays to a Function
To pass multidimensional arrays to a function, only the name of the array is passed to the
function (similar to one-dimensional arrays).
#include <stdio.h>
void displayNumbers(int num[2][2]); void displayNumbers(int num[2][2]) {
int main() { printf("Displaying:\n");
int num[2][2]; for (int i = 0; i < 2; ++i) {
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) {
for (int j = 0; j < 2; ++j) { printf("%d\n", num[i][j]);
scanf("%d", &num[i][j]);
} }
} }
// pass multi-dimensional array to a function }
displayNumbers(num);

return 0;
}

You might also like