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

前端 未结 8 2094
失恋的感觉
失恋的感觉 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:39

    You can use either of these:

    char const* getIt() {
        return "hello";
    }
    
    char * getIt() {
        static char thing[] = "hello";
        return thing;
    }
    
    char * getIt() {
        char str[] = "hello";
        char * thing = new char[sizeof str];
        std::strcpy(thing, str);
        return thing;
    }
    
    shared_array getIt() {
        char str[] = "hello";
        shared_array thing(new char[sizeof str]);
        std::strcpy(thing.get(), str);
        return thing;
    }
    

    The first requires you to not write to the returned string, but also is the simplest you can get. The last uses shared_array which automatically can clean up memory if the reference to the memory is lost (the last shared_array to it goes out of scope). The last and second last must be used if you require a new string everytime you call the function.

提交回复
热议问题