When you pass an array name from a function what is actually being passed and why?

In C programming, you can pass an entire array to functions. Before we learn that, let's see how you can pass individual elements of an array to functions.

Pass Individual Array Elements

Passing array elements to a function is similar to passing variables to a function.

Example 1: Pass Individual Array Elements

#include <stdio.h> void display(int age1, int age2) { printf("%d\n", age1); printf("%d\n", age2); } int main() { int ageArray[] = {2, 8, 4, 12}; // pass second and third elements to display() display(ageArray[1], ageArray[2]); return 0; }

Output

8 4

Here, we have passed array parameters to the display() function in the same way we pass variables to a function.

// pass second and third elements to display() display(ageArray[1], ageArray[2]);

We can see this in the function definition, where the function parameters are individual variables:

void display(int age1, int age2) { // code }

Example 2: Pass Arrays to Functions

// Program to calculate the sum of array elements by passing to a function #include <stdio.h> float calculateSum(float num[]); int main() { float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18}; // num array is passed to calculateSum() result = calculateSum(num); printf("Result = %.2f", result); return 0; } float calculateSum(float num[]) { float sum = 0.0; for (int i = 0; i < 6; ++i) { sum += num[i]; } return sum; }

Output

Result = 162.50

To pass an entire array to a function, only the name of the array is passed as an argument.

result = calculateSum(num);

However, notice the use of [] in the function definition.

float calculateSum(float num[]) { ... .. }

This informs the compiler that you are passing a one-dimensional array to the function.

Pass Multidimensional Arrays to a Function

To pass multidimensional arrays to a function, only the name of the array is passed to the function (similar to one-dimensional arrays).

Example 3: Pass two-dimensional arrays

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

Output

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

Notice the parameter int num[2][2] in the function prototype and function definition:

// function prototype void displayNumbers(int num[2][2]);

This signifies that the function takes a two-dimensional array as an argument. We can also pass arrays with more than 2 dimensions as a function argument.

When passing two-dimensional arrays, it is not mandatory to specify the number of rows in the array. However, the number of columns should always be specified.

For example,

void displayNumbers(int num[][2]) { // code }

Recommended Reading: Call by Reference in C

View Discussion

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Like Article

    A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array’s name.

    In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun(). The below example demonstrates the same. 

    #include <iostream>

    using namespace std;

    void fun(int arr[])

    {

        unsigned int n = sizeof(arr) / sizeof(arr[0]);

        cout << "\nArray size inside fun() is " << n;

    }

    int main()

    {

        int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };

        unsigned int n = sizeof(arr) / sizeof(arr[0]);

        cout << "Array size inside main() is " << n;

        fun(arr);

        return 0;

    }

    #include <stdio.h>

    #include <stdlib.h>

    void fun(int arr[]) 

    {

       unsigned int n = sizeof(arr)/sizeof(arr[0]);

       printf("\nArray size inside fun() is %d", n);

    }

    int main()

    {

       int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};

       unsigned int n = sizeof(arr)/sizeof(arr[0]);

       printf("Array size inside main() is %d", n);

       fun(arr);

       return 0;

    }

    Output

    Array size inside main() is 8 Array size inside fun() is 1

    Therefore in C, we must pass the size of the array as a parameter. Size may not be needed only in the case of ‘\0’ terminated character arrays, size can be determined by checking the end of string character.
    Following is a simple example to show how arrays are typically passed in C:
     

    When you pass an array name from a function what is actually being passed and why?

    #include <iostream>

    using namespace std;

    void fun(int *arr, unsigned int n)

    {

       int i;

       for (i = 0; i < n; i++)

         cout <<" "<< arr[i];

    }

    int main()

    {

       int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};

       unsigned int n = sizeof(arr)/sizeof(arr[0]);

       fun(arr, n);

       return 0;

    }

    #include <stdio.h>

    void fun(int *arr, unsigned int n)

    {

       int i;

       for (i=0; i<n; i++)

         printf("%d  ", arr[i]);

    }

    int main()

    {

       int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};

       unsigned int n = sizeof(arr)/sizeof(arr[0]);

       fun(arr, n);

       return 0;

    }

    Output

    1 2 3 4 5 6 7 8

    Exercise: Predict the output of the below C programs:
    Program 1:

    #include <iostream>

    using namespace std;

    void fun(int arr[], unsigned int n)

    {

        int i;

        for (i = 0; i < n; i++)

            cout << arr[i] << " ";

    }

    int main()

    {

        int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };

        unsigned int n = sizeof(arr) / sizeof(arr[0]);

        fun(arr, n);

        return 0;

    }

    #include <stdio.h>

    void fun(int arr[], unsigned int n)

    {

    int i;

    for (i=0; i<n; i++)

        printf("%d ", arr[i]);

    }

    int main()

    {

    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};

    unsigned int n = sizeof(arr)/sizeof(arr[0]);

    fun(arr, n);

    return 0;

    }

    Output

    1 2 3 4 5 6 7 8

     Program 2:

    #include <iostream>

    using namespace std;

    void fun(int* arr)

    {

        int i;

        unsigned int n = sizeof(arr) / sizeof(arr[0]);

        for (i = 0; i < n; i++)

            cout << " " << arr[i];

    }

    int main()

    {

        int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };

        fun(arr);

        return 0;

    }

    #include <stdio.h>

    void fun(int *arr)

    {

       int i;

       unsigned int n = sizeof(arr)/sizeof(arr[0]);

       for (i=0; i<n; i++)

         printf("%d  ", arr[i]);

    }

    int main()

    {

       int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};

       fun(arr);

       return 0;

    }

    Output

    1 2

    According to the processor, size of pointer changes for  32 bit computer it assigns 4 bytes to pointer then output becomes 1.

    Program 3:

    #include <iostream>

    #include <string.h>

    using namespace std;

    void fun(char* arr)

    {

        int i;

        unsigned int n = strlen(arr);

        cout << "n = " << n << endl;

        for (i = 0; i < n; i++)

            cout << arr[i] << " ";

    }

    int main()

    {

        char arr[] = "geeksquiz";

        fun(arr);

        return 0;

    }

    #include <stdio.h>

    #include <string.h>

    void fun(char *arr)

    {

       int i;

       unsigned int n = strlen(arr);

       printf("n = %d\n", n);

       for (i=0; i<n; i++)

         printf("%c  ", arr[i]);

    }

    int main()

    {

       char arr[] = "geeksquiz";

       fun(arr);

       return 0;

    }

    Output

    n = 9 g e e k s q u i z

    Program 4: 

    #include <bits/stdc++.h>

    #include <iostream>

    using namespace std;

    void fun(char* arr)

    {

        int i;

        unsigned int n = strlen(arr);

        cout << "n = " << n << "\n";

        for (i = 0; i < n; i++)

            cout << " " << arr[i];

    }

    int main()

    {

        char arr[]

            = { 'g', 'e', 'e', 'k', 's', 'q', 'u', 'i', 'z' };

        fun(arr);

        return 0;

    }

    #include <stdio.h>

    #include <string.h>

    void fun(char *arr)

    {

       int i;

       unsigned int n = strlen(arr);

       printf("n = %d\n", n);

       for (i=0; i<n; i++)

         printf("%c  ", arr[i]);

    }

    int main()

    {

       char arr[] = {'g', 'e', 'e', 'k', 's', 'q', 'u', 'i', 'z'};

       fun(arr);

       return 0;

    }

    Output

    n = 11 g e e k s q u i z

    NOTE: The character array in the above program is not ‘\0’ terminated. (See this for details)

    Now These were some of the common approaches that we use but do you know that there is a better way to do the same. For this, we first need to look at the drawbacks of all the above-suggested methods:

    Drawbacks:

    • A major drawback of the above method is compiler has no idea about what you are passing. What I mean here is for compiler we are just passing an int* and we know that this is pointing to the array but the compiler doesn’t know this.
       
    • To verify my statement you can call for-each loop on your array. You will surely get an error saying no callable begin, end function found.
      This is because the passing array is like actually passing an integer pointer and it itself has no information about the underlying array hence no iterator is provided.

    Template Approach (Reference to Array):

    This method retains all information about the underlying array. This method is majorly based on reference to an array but using this with templates optimizes our method. Template dependency actually calculates the length of the array automatically at the time of function call so that it can be used to create a reference because a reference to an array must know the size of the array.

    Here Template is used for template argument deduction.

    #include <iostream>

    using namespace std;

    template <size_t N> void print(int (&a)[N])

    {

        for (int e : a) {

            cout << e << endl;

        }

    }

    int main()

    {

        int a[]{ 1, 2, 3, 4, 5 };

        print(a);

    }

    Here you can see why we need template argument deduction. For a base to create a reference to an array so that we can take an array as a parameter. 

    Related Articles:

    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed here.