Since I can't return a local variable, what's the best way to return a string from a C or C++ function?

前端 未结 8 2111
失恋的感觉
失恋的感觉 2020-11-30 05:19

As a follow-up to this question:

From what I\'ve seen, this should work as expected:

void greet(){
  char c[] = \"Hello\";
  greetWith(c);
  return;
         


        
8条回答
  •  广开言路
    2020-11-30 05:37

    Depends if the embedded environment has a heap or not, if so, you should malloc as follows:

    char* greet()
    {
      char* ret = malloc(6 * sizeof(char)); // technically " * sizeof(char)" isn't needed since it is 1 by definition
      strcpy(ret,"hello");
      return ret;
    }
    

    Note that you should later call free() to clean up. If you don't have access to dynamic allocation, you will need to make it a global, or a variable on the stack, but further up the call stack.

提交回复
热议问题