将函数字符串返回main

ᴜsᴇ*_*sᴇʀ -1 c string program-entry-point function

我想从函数(在示例funzione中)返回一个字符串到main.这该怎么做?谢谢!

#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;
}
Run Code Online (Sandbox Code Playgroud)

[已编辑]对于那些需要它的人来说,以前代码的完整版本(但没有stringMAIN)是:

#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\n", ptr);

    free (ptr);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

mcl*_*fix 6

字符串是一个可变长度的内存块,C不能返回这样的对象(至少不会破坏与假定字符串无法返回的代码的兼容性)

您可以返回指向字符串的指针,在这种情况下,您有两个选项:

选项1.在函数内动态创建字符串:

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

在这种情况下,接收结果字符串的函数负责释放用于构建它的内存.如果不这样做,将导致程序中的内存泄漏.

int main()
{
  char *str;

  str = funzione();
  /* do stuff with str */
  free (str);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

选项2.在函数内创建一个静态字符串并返回它.

char *funzione (void)
{
  static char str[MAXLENGTHNEEDED];

  strcpy (str, "Example");
  return str;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您不需要释放字符串,但请注意,您将无法从程序中的不同线程调用此函数.此功能不是线程安全的.

int main()
{
  char *str;

  str = funzione();
  /* do stuff with str */
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

请注意,返回的对象是指向字符串的指针,因此在两个方法中,接收结果的变量funzione()不是char数组,而是指向char数组的指针.