c - C中文字字符串的内存使用

标签 c string memory compiler-construction string-literals

当您将字符串直接传递给参数中的函数而不是指向字符数组的指针时,编译器如何管理内存?

例子:

static const char myString[LENGTH] = "A string";
myFunction(myString);

和:

myFunction("A string");

通过指针传递静态常量(很可能存储在 ROM 中)是否会在 RAM 使用方面产生显着优势?

当传递字符串文字时,它是完全复制为 sizeof(myString) 的局部变量还是编译器“知道”通过引用传递它,因为在 C 中数组总是通过引用传递?

最佳答案

该标准没有规定如何使用字符串文字,或者即使在不同部分使用的相同字符串文字是否会被共享。它只是说它们具有静态存储持续时间并且修改它们是未定义的行为。否则,字符串文字只是一个字符数组,并会相应地运行。

这包含在 C99 标准草案 6.4.5 String literals 部分:

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals.66) The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char,

和:

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

在分配给 myString 的情况下,它将被复制到为 myString 分配的内存中,这在 6.7.8 部分中介绍 < em>初始化说:

An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

关于c - C中文字字符串的内存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25068639/

相关文章:

c++ - 是否强制使用短路逻辑运算符?和评价顺序?

c - 单位矩阵生成器用错误的值填充矩阵

c++ - 无法将内存分配给 C++ 中的唯一地址

java - 从文本文件中获取格式化数字的简单方法?

c++ - 优化长时间的内存读写

android - 应用程序长时间恢复时应用程序崩溃

将简单的 C#define 转换为 Rust 常量

c - Linux 中 WaitForSingleObject() 和 ResetEvent() 的等效性

java - 如何从字母数字文本中删除前导零?

string - gsubbing 一个字符串,其模式包含 Lua 中的换行符