[c++] Passing Arrays to Function in C++

#include <iostream>
using namespace std;

void printarray (int arg[], int length) {
    for (int n = 0; n < length; n++) {
        cout << arg[n] << " ";
        cout << "\n";
    }
}

int main ()
{
     int firstarray[] = {5, 10, 15};
     int secondarray[] = {2, 4, 6, 8, 10};
     printarray(firstarray, 3);
     printarray(secondarray, 5);

     return 0;
}

This code works, but I want to understand how is the array being passed.

When a call is made to the printarray function from the main function, the name of the array is being passed. The name of the array refers to the address of the first element of the array. How does this equate to int arg[]?

This question is related to c++

The answer is


firstarray and secondarray are converted to a pointer to int, when passed to printarray().

printarray(int arg[], ...) is equivalent to printarray(int *arg, ...)

However, this is not specific to C++. C has the same rules for passing array names to a function.


The simple answer is that arrays are ALWAYS passed by reference and the int arg[] simply lets the compiler know to expect an array


The question has already been answered, but I thought I'd add an answer with more precise terminology and references to the C++ standard.

Two things are going on here, array parameters being adjusted to pointer parameters, and array arguments being converted to pointer arguments. These are two quite different mechanisms, the first is an adjustment to the actual type of the parameter, whereas the other is a standard conversion which introduces a temporary pointer to the first element.

Adjustments to your function declaration:

dcl.fct#5:

After determining the type of each parameter, any parameter of type “array of T” (...) is adjusted to be “pointer to T”.

So int arg[] is adjusted to be int* arg.

Conversion of your function argument:

conv.array#1

An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The temporary materialization conversion is applied. The result is a pointer to the first element of the array.

So in printarray(firstarray, 3);, the lvalue firstarray of type "array of 3 int" is converted to a prvalue (temporary) of type "pointer to int", pointing to the first element.


I just wanna add this, when you access the position of the array like

arg[n]

is the same as

*(arg + n) than means an offset of n starting from de arg address.

so arg[0] will be *arg