How do you pass C language arrays to parameters?
In the C language, arrays can be passed to a function parameter in two ways:
- Passing a pointer to an array: When passing an array, what is actually passed is the starting address of the array. The formal parameter can be declared as a pointer to the data type of the array. Inside the function, you can access the elements of the array using the pointer.
The sample code is as follows:
#include <stdio.h>
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
printArray(arr, size);
return 0;
}
The output is: 1 2 3 4 5
- Passing the array’s pointer and its length as parameters: In addition to passing the array’s pointer, you can also pass the array’s length as a parameter. This way, you can access the array’s elements within the function and know the length of the array.
The sample code is as follows:
#include <stdio.h>
void printArray(int *arr, int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
printArray(arr, size);
return 0;
}
The output remains the same: 1 2 3 4 5
Both methods can achieve passing arrays, the choice between the two depends on specific requirements and programming habits.