c - 我想知道为什么不需要为字符串绑定(bind)内存就可以工作

标签 c string pointers string-literals

大家好,我最近学习了 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/

相关文章:

c - 动态内存分配的字符指针分析

c - 堆排序的比较次数

c - 为什么这个程序会这样呢? C

javascript - 按\n 分割时忽略尾随换行符和前导换行符?

Python - 密文长度必须等于 key 大小 - 将其传递到服务器后的不同字符串长度

c - 这两个版本的代码(指针算术和 unicode)有什么区别?

c - 用 C 语言的泰勒级数逼近 Sine(x) 并遇到很多问题

c - 管道没有得到 EOF

java - 计算字符串数组的每个字符串中的反斜杠

c - 在 C 中获取 __regvar 变量的地址