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:

If I uncomment the lines inside the "getID" function, then the "ID" value gets printed:
I don't know what am I missing over here. Thanks in advance and happy holidays.

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:
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:
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 modifierstaticto keep the array in memory even after returning from the function.