rerun a char Concatenation

2018-08-14 16:00:24

My goal is to create a function that concatenate 2 chars into 1, and return it as MQTT subscribe. I get a difference between the results inside and outside the function ( I'm new to Arduino ), and I can't find why:


// Update variable below:

const char *direction = "up";

const char* clientID = "Sonoff";


const char *client_temp = "HomePi/Dvir/Windows/";

const char* outTopic = "HomePi/Dvir/Messages";

//const char* outTopic2 = "HomePi/Dvir/Windows/ESP32";

const char* inTopic2 = "HomePi/Dvir/Windows/All";

char *inTopic;

void setup() {


// len(create_topic(client_temp, clientID));

inTopic = create_topic(client_temp, clientID);



char *create_topic(char *chr1, char *chr2){ . // added *

char topic[strlen(chr1) +strlen(chr2)+1];



return topic;


void loop() {

// put your main code here, to run repeatedly:


Result ( both line should have bee

  • The concatenation is working fine in both instances.

    What is wrong, though, is that you can't return a pointer to a locally declared array from a function. That array no longer exists when you leave the function.

    The thing to remember with arrays is that you never pass the actual array to or from a function. All you pass is a pointer to the memory address where the array is. If you allocate an array in a function that memory is allocated on the stack. When you return the array from the function you return an address that is (currently) within the stack. When you leave the function all memory allocated on the stack by that function is removed, and that includes your array.

    There are four ways of solving the problem - all of them have their pitfalls.

    Use a global "scratch pad" array that is big enough for any concatenating you may want to do. Do your concatenation in there.

    Declare your array static, which means it's allocated only once and can be returned from the function - bu

    2018-08-14 17:33:51