Arrays in C++ must have their size defined at compile time. There is simply no way around this. If you want something that is resizeable at run-time then you must use a more complicated structure like an STL vector that can allocate memory dynamically. There's an ArduinoSTL port in the Library manager, but using dynamic allocation on a microcontroller can get dicey if you are constantly creating and destroying objects on the heap.
Alternately, if you just want the parent to have a reference to an array of children that is defined elsewhere, use a pointer. Arrays are trivially convertable to a pointer. Then you need a separate member variable to store the number of children so you don't overflow the array boundary.
One possible answer would be to let the parent have a pointer to one child and implement the children as linked lists such that each child also has a pointer to its next sibling
How do you want to process this structure ? Using the parent node to access child nodes as in the example, or do you need to go also from a specific child to its parent ?
Strictly speaking, not allowed in C++11 or older, allowed in C++14 (and C99):
>> avr-g++ -Wall -Wextra -pedantic -std=gnu++11 ... arry.ino
arry.ino:18:19: warning: ISO C++ forbids variable length array 'myArray' [-Wvla]
int myArray[size]; // size is not known at compile time.
>> avr-g++ -Wall -Wextra -pedantic -std=gnu++14 ... arry.ino
(no warnings)
Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.
BulldogLowell:
Strictly speaking, this is not correct. Arrays can be created during program execution without having to determine the size at compile-time.
Good catch, thank you for the correction.
This doesn't help the OP though, because the array size must still be known when the array is declared and allocated. xmen will need to either use my pointer idea or, if it must be resized at run-time, a dynamic solution like a vector or linked list.
Jiggy-Ninja:
Good catch, thank you for the correction.
This doesn't help the OP though, because the array size must still be known when the array is declared and allocated. xmen will need to either use my pointer idea or, if it must be resized at run-time, a dynamic solution like a vector or linked list.