Passing of arrays to a function by G Krishna Chauhan

n C programming, a single array element or an entire array can be passed to a function. This can be done for both one-dimensional array or a multi-dimensional array.

Passing One-dimensional Array In Function:

Single element of an array can be passed in similar manner as passing variable to a function.

C program to pass a single element of an array to function

#include <stdio.h>
void display(int age)
{
    printf("%d", age);
}

int main()
{
    int ageArray[] = { 2, 3, 4 };
    display(ageArray[2]); //Passing array element ageArray[2] only.
    return 0;
}

Output: 4

Passing an entire one-dimensional array to a function
While passing arrays as arguments to the function, only the name of the array is passed (,i.e, starting address of memory area is passed as argument).

C program to pass an array containing age of person to a function. This function should find average age and display the average age in main function.

#include <stdio.h>
float average(float age[]);

int main()​
{
    float avg, age[] = { 23.4, 55, 22.6, 3, 40.5, 18 };
    avg = average(age); /* Only name of array is passed as argument. */
    printf("Average age=%.2f", avg);
    return 0;
}

float average(float age[])
{
    int i;
    float avg, sum = 0.0;
    for (i = 0; i < 6; ++i) {
        sum += age[i];
    }
    avg = (sum / 6);
    return avg;
}

Output: Average age=27.08

Passing Multi-dimensional Arrays to Function:

To pass two-dimensional array to a function as an argument, starting address of memory area reserved is passed as in one dimensional array

#Example: Pass two-dimensional arrays to a function
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main()
{
    int num[2][2], i, j;
    printf("Enter 4 numbers:\n");
    for (i = 0; i < 2; ++i)
        for (j = 0; j < 2; ++j)
            scanf("%d", &num[i][j]);
    // passing multi-dimensional array to displayNumbers function
    displayNumbers(num);
    return 0;
}

void displayNumbers(int num[2][2])
{
    // Instead of the above line,
    // void displayNumbers(int num[][2]) is also valid
    int i, j;
    printf("Displaying:\n");
    for (i = 0; i < 2; ++i)
        for (j = 0; j < 2; ++j)
            printf("%d\n", num[i][j]);
}

Output: 

Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5

No comments:

Post a Comment