-1

I require to build a simple Arduino function that returns either "char*" or "const char*" type and then I need to print that value.

However, I'm facing a problem: when I try to print the function's return value, actually nothing gets printed.

char *getID()
{ 
  char ID[15]{"123456789ABCDE"};

  // The actual value for ID is returned from another 
  // function as a String type, so, for simplicity's sake
  // I'm just using a random string instead of posting here that function
  String str{"EDCBA987654321"};
  
  // Write the String returned value into the ID buffer
  str.toCharArray(ID,str.length());

  
   // The following piece of code actually prints the value: EDCBA987654321
  //Serial.println("print ID from inside the function: ");
  //Serial.println(ID);

  return ID;
}


void setup() {
  Serial.begin(9600);
  while(!Serial);
}

void loop() {
  /**
   * Nothing gets printed when using the return value from the function
   */
   Serial.println("print id as the value returned by the \"getID\" function:");
   Serial.println(getID());
   delay(2000);
}

This is the output on the serial monitor: enter image description here

If I uncomment the lines inside the "getID" function, then the "ID" value gets printed:

enter image description here

I don't know what am I missing over here. Thanks in advance and happy holidays.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Juan_David
  • 126
  • 2
  • 11

1 Answers1

0

There are two solutions for this, it all related to the fundamental understanding of string literal and array in C++, not specific to Arduino.

This will work:

char *getID()
{ 
  char *ID{"123456789ABCDE"};

  return ID;
}

In C++, a string literal has global scope, a pointer to a string literal which has global scope is of course point to the correct string literal in the memory. This is equivalent to directly using a global declared const char *ID{"123456789ABCDE"};.

or alternative this will also work:

char *getID()
{ 
  static char ID[15]{"123456789ABCDE"};

  return ID;
}

The problem with your original code is that ID[15] is an array which has local scope within the function, it is not a string literal, but merely an array of ID[15]{"1", "2", "3"... "E"};. Another problem is that you are returning a pointer to an array which immediately out of the scope when return. Therefore you need the modifier static to keep the array in memory even after returning from the function.

hcheung
  • 3,377
  • 3
  • 11
  • 23
  • you missed the comment " The actual value for ID is returned from another function as a String type, so, for simplicity's sake I'm just using a random string instead of posting here that function" – Juraj Jan 31 '23 at 12:24