Hi,
I read somewhere that some standard C functions do not work as well in the Arduino interface so I decided to see if it was still possible to return an array from a function.
From C language, I know that it is possible to return an array by declaring a variable as static or using malloc. The code that I wrote is shown below:
#define SIZE 10
void setup() {
Serial.begin(9600);
}
// Returning a reversed array with malloc
int *func1(int *x) {
int *p = malloc(sizeof(int)*SIZE);
for (int i = 0; i < SIZE; i++) {
p[i] = x[SIZE - 1 - i]; // Reverse array x and store result in p
}
return p;
}
// Returning a reversed array declared as static
int *func2(int x[]) {
static int p[SIZE] = {0};
for (int i = 0; i < SIZE; i++) {
p[i] = x[SIZE - 1 - i]; // Reverse array x and store result in p
}
return p;
}
void print_array(int *y) {
for (int i = 0; i < SIZE; i++) {
Serial.print(y[i]);
Serial.print(" ");
}
Serial.print("\n");
}
int x[SIZE] = {1,2,3,4,5,6,7,8,9,10};
int *y;
int counter = 0;
int value = 0;
void loop() {
y = func1(x);
Serial.print("Output of function 1: ");
print_array(y);
free(y);
delay(1000);
Serial.println();
Serial.print("Output of function 2: ");
y = func2(x);
print_array(y);
delay(1000);
}
Both of the functions work as expected. However, I am aware that an Arduino program operates a bit differently from a C program since it runs on an embedded system. From the two array functions that I wrote, which method is better when programming an Arduino board?