in the following function instead of the arrays amplitude and duration being static, I want to give their length in the argument of the function then create them inside
QueueArray <Node> setPattern(int amplitude[8],unsigned long duration[8]){
QueueArray <Node> queue;
unsigned long nodeDurationSum = 0;
for (int i=0;i<8;i++){
Node node;
nodeDurationSum = nodeDurationSum + duration[i];
node.setPatternNode(amplitude[i],nodeDurationSum);
queue.enqueue(node);
}
return queue;
}
QueueArray< Node > setPattern( int *amplitude, unsigned long *duration, unsigned count ){
QueueArray< Node > queue;
unsigned long nodeDurationSum = 0;
for ( int i=0;i< count ; ++i ){
Node node;
nodeDurationSum = nodeDurationSum + duration[i];
node.setPatternNode(amplitude[i],nodeDurationSum);
queue.enqueue(node);
}
return queue;
}
However, queue will die every call, do you intend it to be static? As returning it by value could double the allocations it makes ( might use dynamic mem also ). Returning a static local as a reference may help, however you'll need more help as the Arduino core is missing some bits which allow this to work.
A template will allow it, however you may end up with multiple copies of the function code being compiled for different array sizes. Arrays are not passed by value, so the only memory you need to watch is the queue.
If using the template and the queue is meant to be static, you'll need it to be global for each template version to see the same queue, otherwise they each have their own.
template< unsinged N >
QueueArray< Node > setPattern( int amplitude[ N ],unsigned long duration[ N ] ){
QueueArray< Node > queue;
unsigned long nodeDurationSum = 0;
for ( int i=0;i< N ; ++i ){
Node node;
nodeDurationSum = nodeDurationSum + duration[i];
node.setPatternNode(amplitude[i],nodeDurationSum);
queue.enqueue(node);
}
return queue;
}
yacine1991:
instead of the arrays amplitude and duration being static, I want to give their length in the argument of the function then create them inside
If the arrays are local to the function then there's nothing stopping you from declaring them as local automatic variables - as long as you have enough memory available for the stack. The size can be dynamic in the sense that it is determined within the function at runtime but is fixed in the sense that within a given execution of the function, once the variable has been declared the size is fixed.
If the arrays are persistent or global then you could allocate them from the heap and store the address in your static or global variable (wherever you would have declared the array if it had been a fixed size) but I don't know enough about your project to know whether that's a sensible approach to take. If you take the approach you have to design your code to know whether the array has been allocated and what size it is.