将字符串从函数返回到main [英] Return a string from function to main

查看:105
本文介绍了将字符串从函数返回到main的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个字符串从函数(在示例中为 funzione )返回给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;
}

对于需要它的人,以前的代码的完整版本(但没有 stringMAIN )是:

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

    free (ptr);

    return 0;
}

推荐答案

字符串是可变长度的内存块,并且C无法返回此类对象(至少在不破坏与假定无法返回字符串的代码兼容的前提下)

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:

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

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;
}

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

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;
}

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

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.

这篇关于将字符串从函数返回到main的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆