passing an array to a function

Passing an Array to a Function in C

To pass an array to a function in C, you can use either of the following methods:

  1. Pass the array as a pointer:
  2. In this method, you pass the base address of the array to the function.
  3. The function receives the array as a pointer parameter and can access the array elements using pointer arithmetic.
  4. Any modifications made to the array elements within the function will affect the original array.
  5. Here is an example:

```c void modifyArray(int arr, int size) { for (int i = 0; i < size; i++) { arr[i] = 2; // Multiply each element by 2 } }

int main() { int arr[] = {1, 2, 3, 4, 5}; int size = sizeof(arr) / sizeof(arr[0]);

   modifyArray(arr, size);

   // Print modified array
   for (int i = 0; i < size; i++) {
       printf("%d ", arr[i]);
   }

   return 0;

} ```

Output: 2 4 6 8 10

  1. Pass the array as a sized array:
  2. In this method, you pass the entire array to the function as a parameter.
  3. The function receives the array as a sized array parameter, which preserves the size information of the array.
  4. The function can access the array elements using array indexing.
  5. Any modifications made to the array elements within the function will affect the original array.
  6. Here is an example:

```c void modifyArray(int arr[], int size) { for (int i = 0; i < size; i++) { arr[i] *= 2; // Multiply each element by 2 } }

int main() { int arr[] = {1, 2, 3, 4, 5}; int size = sizeof(arr) / sizeof(arr[0]);

   modifyArray(arr, size);

   // Print modified array
   for (int i = 0; i < size; i++) {
       printf("%d ", arr[i]);
   }

   return 0;

} ```

Output: 2 4 6 8 10

These methods allow you to pass an array to a function in C and modify its elements within the function. Remember to pass the size of the array along with the array itself to ensure proper array access and manipulation.