当您将字符串直接传递给参数中的函数而不是指向字符数组的指针时,编译器如何管理内存?
例子:
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/