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

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

    If you need to do this in C++, using std::string as suggested by Greg Hewgill is definitely the most simple and maintainable strategy.

    If you are using C, you might consider returning a pointer to space that has been dynamically allocated with malloc() as suggested by Jesse Pepper; but another way that can avoid dynamic allocation is to have greet() take a char * parameter and write its output there:

    void greet(char *buf, int size) {
        char c[] = "Hello";
    
        if (strlen(c) + 1 > size) {
            printf("Buffer size too small!");
            exit(1);
        }
    
        strcpy(buf, c);
    }
    

    The size parameter is there for safety's sake, to help prevent buffer overruns. If you knew exactly how long the string was going to be, it would not be necessary.

提交回复
热议问题