I read somewhere that if you want a C/C++ function to return a character array (as opposed to std::string), you must return const char* rather than char*. Doing the latter may cause the program to crash.
Would anybody be able to explain whether this is true or not? If it is true, why is returning a char* from a function so dangerous? Thank you.
const char * my_function()
{
....
}
void main(void)
{
char x[] = my_function();
}
If you have a function that returns "string literals" then it must return const char*. These do not need to be allocated on the heap by malloc because they are compiled into a read-only section of the executable itself.
Example:
const char* errstr(int err)
{
switch(err) {
case 1: return "error 1";
case 2: return "error 2";
case 3: return "error 3";
case 255: return "error 255 to make this sparse so people don't ask me why I didn't use an array of const char*";
default: return "unknown error";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With