Passing Unsized Array through function in C++

Viewed 2237

I'm trying to initialize a dynamic array and pass it through a function, but I keep getting errors every-time I do so.

float addLayer(float layers[]){
    float addColor = 0;
    if (std::find(std::begin(layers), std::end(layers), addColor)){
        // run code
        addColor = ...;
    }
    return addColor
}

float layers[] = {0};
newColor = addLayer(layers[]); //line 2

Error I receive:

Expected identifier or '(' on line 2

Any help would be appreciated, thank you

2 Answers
float addLayer(float layers[]);

is equivalent to

float addLayer(float* layers);

i. e. all you have is the pointer. All length information is lost as soon as the array decays to the pointer.

To retain length information, you can pass it in a separate parameter, alternatively, you can pass a reference to array:

template <size_t N>
float addLayer(float(&layers)[N]); // pass reference to array of length N

Additionally, there's a syntax error:

newColor = addLayer(layers[]);
//                        ^^

Layers is already an array (but decays to pointer if passed to pointer version of function), and what you actually do in above line is applying the index operator to the array – however without argument (note that with argument, you'd get a float value, not a pointer any more).

Finally: Both std::array(fixed size) and std::vector(variable size) are better alternatives to raw arrays, prefer using one of these whenever possible.

The problem is you can't pass a C array as an argument to a function -- C does not allow it, so C++ does not either. If you declare a function as taking a C array as a parameter, the compiler silently changes it into a pointer, so you're actually passing a pointer. Thus, calling std::begin and std::end on that pointer argument won't work.

In order to make this work in C++, you need to use a std::array or std::vector instead.

Related