Return a string from function to main

后端 未结 3 1809
南笙
南笙 2020-12-18 17:28

I want to return a string from a function (in the example funzione) to main. How to do this? Thank you!

#include 
#include 

        
相关标签:
3条回答
  • 2020-12-18 17:44

    A string is a block of memory of variable length, and C cannot returns such objects (at least not without breaking compatibility with code that assumes strings cannot be returned)

    You can return a pointer to a string, and in this case you have two options:

    Option 1. Create the string dynamically within the function:

    char *funzione (void)
    {
        char *res = malloc (strlen("Example")+1);  /* or enough room to 
                                                      keep your string */
        strcpy (res, "Example");    
        return res;
    }
    

    In this case, the function that receives the resulting string is responsible for deallocate the memory used to build it. Failure to do so will lead to memory leaks in your program.

    int main()
    {
      char *str;
    
      str = funzione();
      /* do stuff with str */
      free (str);
      return 0;
    }
    

    Option 2. Create a static string inside your function and returns it.

    char *funzione (void)
    {
      static char str[MAXLENGTHNEEDED];
    
      strcpy (str, "Example");
      return str;
    }
    

    In this case you don't need to deallocate the string, but be aware that you won't be able to call this function from different threads in your program. This function is not thread-safe.

    int main()
    {
      char *str;
    
      str = funzione();
      /* do stuff with str */
      return 0;
    }
    

    Note that the object returned is a pointer to the string, so on both methods, the variable that receives the result from funzione() is not a char array, but a pointer to a char array.

    0 讨论(0)
  • 2020-12-18 17:44
    #include <stdio.h>
    #include <string.h>
    
    #define SIZE 10
    
    const char *funzione (void){
        const char *string = "Example";
    
        if(strlen(string) >= SIZE)
            return "";
    
        return string;
    }
    
    int main(void){
        char stringMAIN[SIZE];
    
        strcpy(stringMAIN, funzione());
    
        printf("%s", stringMAIN);
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-18 18:03

    You can do this as

    char *funzione (void)
    {
        char *stringFUNC = malloc(SIZE);
        strcpy (stringFUNC, "Example");
    
        return stringFUNC;
    }  
    

    In main, call it as

    int main()
    {
        char stringMAIN[SIZE];
        char *ptr = funzione ()
        ...
    
        free(ptr);
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题