If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C language, arrays are passed to functions as pointers by default. This means that when an array is passed as an argument to a function, the function receives a pointer to the first element of the array, and not a copy of the entire array.
Here is an example of passing an array by reference using a pointer:
Copy code
#include <stdio.h>
void print_array(int* arr, int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int a[5] = {1, 2, 3, 4, 5};
print_array(a, 5);
return 0;
}
In this example, the print_array()
function takes a pointer to an integer and an integer as arguments. The pointer is pointing to the first element of the array a
, and the integer is the size of the array. The function uses the pointer to access the elements of the array and print them out.
It's also worth noting that when an array is passed as an argument to a function, its size is not passed along with it. If the size of the array is required inside the function, it must be passed as an additional argument.
Another way of passing an array to a function is by using the array name without any index, this will pass the pointer to the first element of the array to the function.
Copy code
#include <stdio.h>
void print_array(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int a[5] = {1, 2, 3, 4, 5};
print_array(a, 5);
return 0;
}
This example is equivalent to the previous one, the only difference is the way the array is passed to the function, but the pointer to the first element of the array is passed to the function in both examples.
Comments: 0