array to function

In C, there are scenarios where you need to pass multiple values of the same type to a function. Rather than passing each value individually, you can pass an array, which simplifies the code and makes it more readable. This is particularly useful in functions that operate on a collection of values, such as sorting algorithms.

Understanding Array Passing

When passing an array to a function, you do not pass the actual array elements. Instead, you pass the reference to the array, which means the function can access and modify the actual array elements. The array name acts as a pointer to the first element of the array.

Syntax for Passing an Array

There are three common ways to declare a function that accepts an array as an argument:

1.Using Blank Subscript Notation:

return_type function(type arrayname[])

2.Specifying Array Size:

return_type function(type arrayname[SIZE])

3.Using Pointers:

return_type function(type *arrayname)

Example: Passing a Single-Dimensional Array

#include <stdio.h>

// Function declaration
void printArray(int arr[], int size);

int main() {
    // Array declaration and initialization
    int numbers[] = {1, 2, 3, 4, 5};
    int size = sizeof(numbers) / sizeof(numbers[0]);

    // Function call
    printArray(numbers, size);

    return 0;
}

// Function definition
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

Output:

1 2 3 4 5

Example: Modifying Array Elements

#include <stdio.h>

// Function declaration
void modifyArray(int arr[], int size);

int main() {
    // Array declaration and initialization
    int numbers[] = {1, 2, 3, 4, 5};
    int size = sizeof(numbers) / sizeof(numbers[0]);

    // Function call
    modifyArray(numbers, size);

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

    return 0;
}

// Function definition
void modifyArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        arr[i] *= 2; // Double each element
    }
}

Output:

2 4 6 8 10