How to change an array in a function in c
To change an array in a function in C, you can pass the array as a parameter to the function and modify its elements within the function. Here's an example:
#include <stdio.h>
void changeArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] = arr[i] * 2; // Modify array elements
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Before modification: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
changeArray(arr, size);
printf("After modification: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
In this example, the changeArray
function takes an array arr
and its size size
as parameters. It then iterates over the elements of the array and multiplies each element by 2 to modify the array. The modified array is then printed in the main
function before and after the modification.
Please note that when passing an array to a function in C, you are actually passing a pointer to the first element of the array. This means that any modifications made to the array within the function will affect the original array in the calling function.
I hope this helps! Let me know if you have any further questions.