Arrays in C++

I've noticed something interesting in C++ programming. I've always done tricky stuff with pointers and references to have functions deal with arrays. Doing exercises again out of a C++ book has shown me an easier way, I didn't even know was there. It's weird to me.

When dealing with arrays, it seems if I pass an array to a function although I cannot return an array - if the array is changed it changes for the whole program. The array is seemingly global. Hence this code works (GCC 4.7)...

#include <iostream>

using namespace std;

int read_inputs(double inputs[], int capacity) {
    int current_size = 0;
    cout << "Please enter values, Q to quit:"<<endl;
    bool more = true;
    while (more)
    {
        double input;
        cin >> input;
        if (cin.fail()) {
            more = false;
        } else if (current_size < capacity) {
            inputs[current_size] = input;
            current_size++;
        }
    }
    return current_size;
}

void multiply(double values[], int size, double factor)
{
    for (int i = 0; i < size; i++)
    {
        values=values * factor;
    }
}

void print(double values[], int size)
{
    for (int i = 0; i < size; i++)
    {
        if (i > 0) {cout << ", ";}
        cout << values;
    }
    cout << endl;
}

int main() {
    const int CAPACITY = 1000;
    double values[CAPACITY];
    int size = read_inputs(values, CAPACITY);
    print(values, size);
    multiply(values, size, 2);
    print(values, size);

    return 0;
}

Yes, this is a feature of both C and C++ - array names automatically decay into pointers where appropriate. When passing an array to a function, the array is never placed on the stack (how would the called function know how large it is?) so instead a pointer is passed, and any modification through the pointer will be seen to the calling function.

2 Likes

yes, passing array is call by reference.Array name without subscript is itself a poinetr.
For c++ refer C++ Basics

Are they ever anything but a pointer? The only difference when it's local is, it knows it's a const one whose base can't be changed...

Yes, there's a difference. A reference in code to a non-subscripted array is evaluated as the address of the first element of the array. That's not quite the same as a pointer. A pointer can be an l-value, a "naked" array reference can't be.

Thus

foo( char *bar )
{
    .
    .
    .
    bar++;
    .
    .
    .
}

is fine, but

foo( char bar[] )
{
    .
    .
    .
    bar++;
    .
    .
    .
}

should (offhand) result in a syntax error, even though both could be called like this:

char a[ 32 ];
   .
   .
   .
foo( a );
   .
   .
   .