从没有malloc的函数返回字符串 [英] returning string from function without malloc

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

问题描述

是否可以在不调用malloc的情况下从函数返回字符串? 我的功能如下:

Is it possible to return string from a function without calling malloc? I have a function as below:

char* getString(){
      char tempStr[20]

      // open file, read char by char and assign to tempStr
      // ....

      char* str = (char*)malloc(sizeof(char)*20);
      strcpy(str, tempStr); // assume this copy the null terminating char as well
      return str;
}

然后,当我调用getString()时,我将返回值分配给char*,然后在完成后将其释放,如下所示:

And then when I call the getString(), I assign the return value to a char*, and then free it when I'm done, just like below:

void randomFunction(){
      char* line = NULL;
      int i = 0;
      while (i < 1000) {
           line = getString();
           // do stuff with line
           free (line);  
           line = NULL;
      }
}

但是,我想知道如果没有malloc,是否有任何方法可以做到这一点?并且,这是从C函数返回字符串的正确方法吗? 我试图做一些关于如何在没有malloc的情况下返回的研究,但是没有找到明确的答案.我是C语言的新手,仍然在学习.

However, I am wondering if there is any way to do this without malloc? And, is this the proper way of returning string from a C function? I tried to do some research regarding how to return without malloc, but didn't find clear answers. I am new to C and still learning.

推荐答案

您不能从函数中返回临时变量,除非您使用malloc,否则在该函数中定义的字符数组 将是临时变量.另一种解决方案是将字符数组作为参数传递给函数,然后将其用作输出参数.

You can not return temporary from a function and unless you use a malloc your character array defined in the function will be a temporary. An alterantive solution is to pass a character array as parameter to the function and use it as output parameter.

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

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