How Arrays Are Passed To Functions In C/C++?

How Arrays Are Passed To Functions In C/C++?

In C++, you cannot pass a whole array as an argument to a function. However, you can pass a pointer to an array by specifying the array’s name. This allows the function to work with the array’s data without making a full copy of it.

In C, when you pass an array to a function, it’s always treated as a pointer to its first element. This behavior is known as “array decay,” and it means that the function receives a pointer to the array’s data rather than a copy of the entire array. Understanding this concept is important when working with arrays in function arguments in C and C++



// CPP Program to demonstrate passing
// an array to a function is always treated
// as a pointer
#include <iostream>
using namespace std;
 
// Note that arr[] for fun is 
// just a pointer even if square
// brackets are used
void fun(int arr[]) // SAME AS void fun(int *arr)
{
    unsigned int n = sizeof(arr) / sizeof(arr[0]);
    cout << "\nArray size inside fun() is " << n;
}
 
// Driver Code
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;
}

Output

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

However, we have to pass the size of the array by considering it as a parameter. Indeed, Size won’t be required except in the case of ‘\0’ terminated character arrays. In such cases, Size can be evaluated by checking the end of the string character.

How Arrays Are Passed in C


#include <iostream>
using namespace std;
 
void fun(int *arr, unsigned int n)
{
   int i;
   for (i = 0; i < n; i++)
     cout <<" "<< arr[i];
}
 
// Driver program
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

Calculating the output of given C programs

Program 1


// 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] << " ";
}
 
// Driver program
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


// Program 2
#include <iostream>
using namespace std;
void fun(int* arr)
{
    int i;
 //Consider the size of pointer as 8 bytes
    unsigned int n = sizeof(arr) / sizeof(arr[0]); 
    for (i = 0; i < n; i++)
        cout << " " << arr[i];
}
 
// Driver program
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
    fun(arr);
    return 0;
}

Output

1  2

In this example, the size of a pointer can vary depending on the architecture of the computer. Specifically, on a 32-bit computer, pointers are often 4 bytes in size.

Program 3

// 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] << " ";
}
 
// Driver program
int main()
{
    char arr[] = "skillvertexquiz";
    fun(arr);
    return 0;
}

Output

n = 9
skill vertexq u i z 

Program 4

// 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];
}
 
// Driver program
int main()
{
    char arr[]
        = { 's', 'k', 'i', 'l', 'l', 'q', 'u', 'i', 'z' };
    fun(arr);
    return 0;
}

Output

n = 9
 s k i l l q u i z

One of the drawbacks of passing arrays as pointers to functions is that the compiler doesn’t have information about the array’s size or structure. From the compiler’s perspective, it sees a pointer to an element but doesn’t know the size or shape of the array. This limitation can lead to issues such as not being able to use standard library functions like begin and end on the array because there’s no built-in understanding of the array’s structure.

When you pass an array as a pointer, you lose some of the built-in safety and convenience features that come with standard container types, like vectors in C++. This can make it more error-prone and less intuitive to work with arrays in certain cases.

To address these issues, you can use other approaches like passing the size of the array along with the pointer or using standard library containers when possible, such as std::vector in C++, which provides more safety and convenience in handling dynamic arrays.

Template Approach (Reference to Array):

  • This method is based on passing a reference to an array, which allows retaining information about the array’s size and structure.
  • The use of templates, specifically template argument deduction, optimizes this method. Templates enable the automatic calculation of the length of the array at the time of function call, making it possible to create a reference to the array. This is important because a reference to an array must know the size of the array it refers to.

In C++, templates are a powerful feature that allows you to write generic and type-safe code. By using templates in this context, you can create functions that work with arrays of various sizes and types, providing more flexibility and safety in your code.



// CPP Program to demonstrate template approach
#include <iostream>
using namespace std;
 
template <size_t N> void print(int (&a)[N])
{
    for (int e : a) {
        cout << e << endl;
    }
}
 
// Driver Code
int main()
{
    int a[]{ 1, 2, 3, 4, 5 };
    print(a);
}

Output

1
2
3
4
5

FAQ- How Arrays Are Passed To Functions In C/C++?

Q1. Can arrays be passed to functions by value in C++?

Ans. You can’t pass an array by value in C/C++ because there’s no built-in way to track the array’s size. Unlike classes with constructors, arrays lack this information, making it impossible for a function to know how much memory to allocate or what to copy.

Q2. How to pass an array to a function in C with example?

Ans. 1.#include<stdio.h>
2. int minarray(int arr[],int size){
3.int min=arr[0];
4.int i=0;
5.for(i=1;i<size;i++){
6. if(min>arr[i]){
7.min=arr[i];
}

Q3. How are array variables passed to functions in C?

Ans. To pass an array to C functions, you supply a reference to the array’s base address. This allows the function to work with the array’s data using a pointer. Multidimensional arrays can also be passed to C methods using pointers. This concept holds for arrays with multiple dimensions, such as 2D or 3D arrays. The pointers provide access to the array elements in a structured manner, allowing functions to manipulate the data effectively.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment