When an array is passed to a function, its name is converted to a pointer to its first element. The function can access and modify the original array elements through that pointer. The array length is typically passed as a separate argument.
#include <stdio.h>
void displayArray(const int arr[], int size)
{
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
void updateArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
arr[i] *= 2;
}
}
int main(void)
{
int numbers[] = {10, 20, 30, 40};
int size = sizeof(numbers) / sizeof(numbers[0]);
printf("Original array: ");
displayArray(numbers, size);
updateArray(numbers, size);
printf("Updated array: ");
displayArray(numbers, size);
return 0;
}
Example Output #
Original array: 10 20 30 40
Updated array: 20 40 60 80
Explanation #
The function parameter:
void displayArray(const int arr[], int size)
accepts an array’s elements for reading. In a function parameter list, const int arr[] is adjusted to const int *arr. The const qualifier prevents modification of the elements through this parameter.
The function:
void updateArray(int arr[], int size)
accepts a pointer to modifiable integers. The statement:
arr[i] *= 2;
updates the original array element because the pointer refers to the caller’s array.
Passing Arrays to Functions #
| Parameter declaration | Meaning |
|---|---|
int arr[] |
Pointer to modifiable int elements |
const int arr[] |
Pointer to const int elements |
int arr[], int size |
Array access with an explicit element count |
int *arr |
Equivalent parameter type to int arr[] |
Important: The array’s length is not automatically passed to the function. Inside displayArray() or updateArray(), sizeof(arr) gives the size of the pointer parameter, not the size of the original array. Passing the element count separately allows the function to iterate within the intended bounds.