大家好,我最近学习了 C 编程,但我一直停留在理解指针上。据我所知,要在指针中存储一个值,您必须将内存(使用 malloc)绑定(bind)到您要存储的值的大小。鉴于此,以下代码不应该工作,因为我没有分配 11 字节的内存来存储我的 11 字节大小的字符串,但由于某种超出我理解的原因,它工作得很好。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
char *str = NULL;
str = "hello world\0";
printf("filename = %s\n", str);
return 0;
}
最佳答案
在这种情况下
str = "hello world\0";
str
指向 chars
数组的第一个元素的地址,用 "hello world\0"
初始化。换句话说,str
指向一个“字符串文字”。
根据定义,数组已分配且第一个元素的地址必须“有效”。
引用 C11
,章节 §6.4.5,字符串文字
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.78) 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, and are initialized with the individual bytes of the multibyte character sequence. [....]
内存分配仍然发生,只是您未明确(通过内存分配器函数)。
就是说,末尾的 "...\0"
是重复的,正如上面提到的(在引用的第一条语句中),默认情况下,数组将以 null 结尾.
关于c - 我想知道为什么不需要为字符串绑定(bind)内存就可以工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43891117/