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

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

    From what I've read the safest option is to make the caller responsible for allocating memory to hold the string. You must also check if the buffer is large enough to hold your string:

    char *greet(char *buf, int size) {
         char *str = "Hello!"
         if (strlen(str) + 1 > size) { // Remember the terminal null!
              return NULL;
         } 
         strcpy(buf, str);
         return buf;
    }
    
    void do_greet() {
        char buf[SIZE];
        if (greet(buf, SIZE) == NULL) {
            printf("Stupid C");
         } 
         else {} // Greeted!
    }
    

    A ton of work for a simple task... but there's C for you :-) Oops! Guess I was beaten by random_hacker...

提交回复
热议问题