I'm trying to figure out how to return an array from a function.
I can return the array itself with the below code but I can't figure out how to recieve an element from that array.
void setup() {
// put your setup code here, to run once:
Serial.begin (115200);
}
void loop() {
// put your main code here, to run repeatedly:
int ret = Test();
Serial.println(ret);
}
int Test(){
int test[] = {1,2,3};
return test;
}
As stated, use pointers. But, then the local variable being returned must be 'static'. Also, you need some way of knowing the array's size in the calling function:
void setup() {
Serial.begin (115200);
}
void loop() {
int *returnedArray;
returnedArray = Test();
for (uint8_t i = 0; i < 3; i++) {
Serial.println(returnedArray[i]);
}
}
int *Test() {
static int test[] = {1, 2, 3};
return test;
}
As also previously stated, a more common technique would be to allocate the array storage in the calling program and pass a pointer to it (along with array size) to the function:
void setup() {
Serial.begin (115200);
}
void loop() {
const uint8_t arraySize = 3;
int myArray[arraySize];
test(myArray, arraySize);
for (uint8_t i = 0; i < 3; i++) {
Serial.println(myArray[i]);
}
}
void test(int *theArray, size_t numElements) {
for (uint8_t i = 0; i < numElements; i++) {
theArray[i] = i;
}
}
gfvalvo:
As also previously stated, a more common technique would be to allocate the array storage in the calling program and pass a pointer to it (along with array size) to the function:
void setup() {
Serial.begin (115200);
}
void loop() {
const uint8_t arraySize = 3;
int myArray[arraySize];
test(myArray, arraySize);
for (uint8_t i = 0; i < 3; i++) {
Serial.println(myArray[i]);
}
}
void test(int *theArray, size_t numElements) {
for (uint8_t i = 0; i < numElements; i++) {
theArray[i] = i;
}
}
I do have one more question that will help me understand your code. What dose the "*" mean in front of *theArray? The code does work without it.
KrafterHD:
I do have one more question that will help me understand your code. What dose the "*" mean in front of *theArray? The code does work without it.
Thanks
The * indicates a pointer.
Without it, the code DOES NOT work.
It won't even compile.
KrafterHD:
I do have one more question that will help me understand your code. What dose the "*" mean in front of *theArray? The code does work without it.