I am trying to achive concatenation of several char c[], for what I build a function that accepts a pointer to an array of char c[], makes the concatenation, and returns a char r[] as result (a working sketch is attached at the end of this comment)
But what I am experimenting I can not understand... >:( The function seems to work properly in some defined cases, although what I change seems to me it should have no influence at all...
case A1 B1 B2 Result
1 no no no wrong
2 no no yes right
3 yes yes yes right
("no" means commented, "yes" means uncommented)
Notice that "debug" is defined in (A1) as false, so case (1) and (3) should behave the same...
Has anyone idea what is it hapenning here??
Thanks a lot!
// Tested under environment: Arduino Wemos D1 (v1) (= UNO compatible)
boolean debug = false; // (A1)
char* concaten(char* g[], int n) {
int L = 1;
for(int i=0; i<n; i++) {
if(debug) // (B1)
Serial.println("strlen(g["+(String)i+"]): "+ (String)strlen(g[i])); // (B2)
L += strlen(g[i]);
}
char temp[L];
for(int i=0; i<n; i++) {
temp[i] = '\0'; // same as = (char) 0
}
strcpy(temp, g[0]);
for(int i=1; i<n; i++) {
strcat(temp, g[i]);
}
Serial.println("Intern: "+ (String)temp);
return temp;
}
void setup() {
Serial.begin(115200);
delay(10);
while (!Serial);
char h0[] = "000";
char h1[] = "11";
char h2[] = "22222";
char h3[] = "";
char h4[] = "444444444";
char* g[] = { h0, h1, h2, h3, h4 };
int elements = sizeof(g)/sizeof(g[0]);
Serial.println("Extern concaten: "+ (String)concaten(g, elements));
}
void loop() {
;
}