Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

c - Return a string from function to main

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

#include <stdio.h>
#include <string.h>

#define SIZE (10)

/* TODO*/ funzione (void)
{
    char stringFUNC[SIZE];

    strcpy (stringFUNC, "Example");

    return /* TODO*/;
}


int main()
{
    char stringMAIN[SIZE];

    /* TODO*/

    return 0;
}

[EDITED] For those who need it, the complete version of the previous code (but without stringMAIN) is:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE (10)

char *funzione (void)
{
    char *stringa = malloc(SIZE);
    strcpy (stringa, "Example");

    return stringa;
} 

int main()
{
    char *ptr = funzione();

    printf ("%s
", ptr);

    free (ptr);

    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...