Hi mbeders,
I am working on an application where I need to control 12 servos. At the minute I'm calculating their positions in a function and need a way to return all 12 positions. At the minute I've created a structure that contains all the positions and am returning the structure from the function.
This seems a little clunky and I thought it would be a bit more elegant to create an array containing the values and return a pointer to the start of the array. Like this...
#include "mbed.h"
Serial pc(USBTX,USBRX);
int* pointer_print(void) {
int bar[6] = {1,2,3,4,5,6}; // local array of integers
return bar;
}
int main() {
int* foo = pointer_print(); // get the pointer
for (int i=0; i<6; i++) {
pc.printf("%d ",foo[i]);
}
}
My question is because the array 'bar' is local to the pointer_print function it will be destroyed when the pointer is returned (but the memory location content will not be overwritten or lost). I will be doing this a lot and am worried that if the mbed then uses that memory location for something else my servo position data will become corrupt? Can I minimise this risk by using the data right away? Is there a better way of doing it?
Is this right or am I worrying about nothing?
Hi mbeders,
I am working on an application where I need to control 12 servos. At the minute I'm calculating their positions in a function and need a way to return all 12 positions. At the minute I've created a structure that contains all the positions and am returning the structure from the function.
This seems a little clunky and I thought it would be a bit more elegant to create an array containing the values and return a pointer to the start of the array. Like this...
My question is because the array 'bar' is local to the pointer_print function it will be destroyed when the pointer is returned (but the memory location content will not be overwritten or lost). I will be doing this a lot and am worried that if the mbed then uses that memory location for something else my servo position data will become corrupt? Can I minimise this risk by using the data right away? Is there a better way of doing it?
Is this right or am I worrying about nothing?