How to pass array as function argument in C?
In C, an array can be passed to a function in two ways:
- Pass by value: This method passes a copy of the array to the function. Any changes made to the array inside the function do not affect the original array.
Example:
#include <stdio.h>
void print_array(int arr[], int size);
int main()
{
int numbers[5] = {1, 2, 3, 4, 5};
print_array(numbers, 5); // will print "1 2 3 4 5"
return 0;
}
void print_array(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
printf("%d", arr[i]);
}
}
- Pass by reference: This method passes a pointer to the array to the function. Any changes made to the array inside the function will affect the original array.
#include <stdio.h>
void modify_array(int *arr, int size);
int main()
{
int numbers[5] = {1, 2, 3, 4, 5};
modify_array(numbers, 5); // will double the value of each element in the array
for (int i = 0; i < 5; i++)
{
printf("%d ", numbers[i]);
}
return 0;
}
void modify_array(int *arr, int size)
{
for (int i = 0; i < size; i++)
{
arr[i] = arr[i] * 2;
}
}
In the above examples, the function print_array
takes an array of integers and its size as arguments and prints all the elements of the array. The function modify_array
takes a pointer to an array of integers and its size as arguments and doubles the value of each element of the array.
It's important to note that when an array is passed to a function, only the address of the first element of the array is passed, not the entire array.