从C函数返回字符串 [英] Returning string from a C function

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

问题描述

我有一个简单的代码.

#define MY_STRING "String example"

char* string_return_function()
{
    return MY_STRING;
}

上面的代码有效,但是我不确定如何.我认为string_return_function()返回一个本地地址,一旦函数退出,该地址将被释放.

The above code works but I am not sure how. I think the string_return_function() returns a local address, which would gets freed once the function exits.

推荐答案

不,不是这样的.

字符串文字存储在程序运行期间一直存在的内存中,因此该函数只返回指向字符串常量的指针.

String literals are stored in memory that persists for as long as the program runs, so the function just returns a pointer to the string constant.

在运行时不会发生字符串创建/初始化,也不会复制任何字符.它只是返回一个指针,该函数的机器代码可能只是几条指令.

There is no string creation/initialization happening at run-time, no characters are copied around. It's just returning a pointer, the function's machine code is likely just a couple of instructions.

例如,这是我从 https://assembly.ynh.io/获得的(清理后的)x86代码. :

string_return_function:
  movl  $.LC0, %eax
  ret

.LC0只是存放字符串的位置.因此,这是2条指令,包括从functin顶板/样板板返回的内容.相当有效. :)

Where .LC0 is simply a location holding the string. So, that's 2 instructions including the return from functin overhead/boilerplate. Pretty efficient. :)

您正在考虑:

char * bad_code(void)
{
  char response[] = MY_STRING;
  return response;
}

这是错误代码,因为它返回了本地数组.所讨论的数组从字面量初始化都没关系,这不是要返回的内容.

This is bad code since it returns a local array. It doesn't matter that the array in question is initialized from the literal, that's not what's being returned.

此外,不要以str开头的函数命名,所有这些名称都保留; C11草案说:

Also, don't name your function starting with str, all such names are reserved; the C11 draft says:

strmemwcs开头的函数名以及小写字母 字母可以添加到<string.h>标头中的声明中.

Function names that begin with str, mem, or wcs and a lowercase letter may be added to the declarations in the <string.h> header.

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

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