Code Point Blog

Iam presenting here ,all type of knowledge if you want to interest knowing about any topic then click below thumbnail view button and knowing.

All Chapter Back to Home Page

Passing array to function

In C language, you can pass an array to a function as an argument. When you pass an array to a function, you are essentially passing a pointer to the first element of the array. This means that the function can access and manipulate the original array directly, even though the array's size is not explicitly passed.

There are two common ways to pass an array to a function in C:

1.Passing by Reference (Using Pointers) :You can pass the array to the function as a pointer. The function's parameter should be a pointer type, and you need to pass the array's address (pointer) as the argument

Here's an example of passing an array to a function using pointers:

    
        #include <stdio.h>
        // Function that modifies the array 
        void modifyArray(int* arr, int size) { 
        for (int i = 0; i < size; i++) 
         {
             arr[i]=arr[i] * 2;
         } 

         } 
             
        int main(){ 
        int numbers[]={1, 2, 3, 4,5 }; 
        int size=sizeof(numbers) / sizeof(numbers[0]); 
        printf("Original Array: "); 
for (int i = 0; i < size; i++) { printf(" %d ", numbers[i]); } printf(" \n"); modifyArray(numbers, size); printf("Modified Array: "); for (int i = 0; i < size; i++) { printf(" %d ", numbers[i]); } printf(" \n"); return 0; } } Output: Original Array: 1 2 3 4 5 Modified Array: 2 4 6 8 10

In this example, the `modifyArray` function takes a pointer to an integer (`int* arr`) and the size of the array (`int size`) as parameters. The function modifies the elements of the array directly.

2.Passing by Value (Using Array) :You can pass the array to the function as an array directly. The function's parameter should be an array type, and you can pass the array itself as the argument. Here's an example of passing an array to a function using the array itself:

    
    #include <stdio.h>
    // Function that prints the array 
    void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++)
        {
        printf("%d ", arr[i]);
        }
        printf(" \n");
        }

        int main() {
        int numbers[]={1, 2, 3, 4, 5};
        int size=sizeof(numbers) / sizeof(numbers[0]);
        printf("Array Elements: ");
        printArray(numbers, size);

        return 0;
        }

        Output:
        Array Elements: 1 2 3 4 5
                                            
    
    

In this example, the `printArray` function takes an array of integers (`int arr[]`) and the size of the array (`int size`) as parameters. The function simply prints the elements of the array.