Initializing Array

Assume there is a variable int size that is mutable and changing globally. In a function if I write int array[size]={0} does this make the array of length size filled with 0 ?

And is this function valid?

void func(int size)
{int array[size];}

I have read that variable allocation might not be allowed in Arduino Boards but ESP32 boards allow it. Can anyone verify where it works.

Populates the first element with the value zero.

You can, in your IDE.

This size is local to func() different from a global size and must be passed to func()

1 Like

this is more or less explicitly initializing the first element of the the array to zero and the remainder to zero by default. More often this is just written int array [size] = {};

but its value is when initializing to non-zero value

int array [] = { 13, 10, 9, 11, 12 };
const int ArraySz = sizeof(array)/sizeof(int);

this also works with arrays of structs

struct  TurnoutDefSt {
    int ServoPin;
    int TogglePin;

    int Normal;
    int Thrown;

    int swPos;
}
turnoutDef [] = {
    {10, A2, 75, 130},
    {11, A3, 80, 130}
};
const int NUM_SERVOS = sizeof(turnoutDef)/sizeof(TurnoutDefSt);
1 Like

That works because the array will be constructed on the stack when the function is called.

This function is valid, but perfectly useless. It creates an array named array, that will local to that function and will be deleted just after creation.

Also, unlike a global variable, this (local) array will NOT be initialized to zeros.

1 Like

Not always. This behaviour is compiler specific. See Basic C++ Array question

As other have said, our compiler supports VLA (variable length arrays) and so the code will work.

The array is on the stack and its scope is local to the function so when the function terminates the array is discarded. I’m assuming you intend to use it only with some other code that will be in the function too.

Note that when programming on small microcontrollers, it’s best to allocate your arrays to the maximum size you intend to support right from the start. This way, you avoid memory issues during execution, since memory on these devices is limited and unpredictable allocations at runtime can quickly cause problems. If your code might need that much memory at any point, you need to make sure it will be there so it’s best to have that reserved and available from the beginning. This ensures your program stays stable and avoids hard-to-track bugs like overflows or memory fragmentation.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.