2

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

Cristian
  • 495
  • 2
  • 9
  • 35
  • 1
    C++ does not have dynamic arrays. Use a vector instead. Also, you do not need to include the brackets for arrays passed as function arguments. – James Nov 15 '18 at 02:37
  • `std::array` and `std::vector` in some cases do not work. To handle `std::array` you have to have a template function. Templates bloat binary with duplicated code. i.e. if you pass array of 2 and of 3, you're gonna to have two instantiations inside your binary. If you use vector, you have to pass it by `const&`. Pointer to pointer.. nah.. `std::span` (C++20) will help. From my point of view It totally makes sense to use unsized array as an argument parameter. The difference to pointer is that in such way you tell to caller that you do not expect NULL pointer (however NULL still can be passed). – Dmytro Ovdiienko Aug 06 '20 at 15:26

2 Answers2

4
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.

Aconcagua
  • 24,880
  • 4
  • 34
  • 59
1

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.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226