c - 这两个初始化是等价的吗?

标签 c string pointers

char *str = "String!";
char *str = (char []){"String!"};

这两个初始化是等价的吗?如果不是,它们之间有什么区别?

最佳答案

Are these two initializations equivalent?

没有。

If not, what is the difference between them?

两者之间的主要区别之一是您不能修改 str 的对象。在第一段代码中指向,而在第二段中,您可以。

尝试在 C 中修改字符串文字是未定义的行为。所以在这种情况下

char *str = "String!";

如果您尝试修改 str 指向的对象,它将调用 UB。

如果是

char *str = (char []){"String!"};

然而,(char[]){"String!"}是一个复合文字,其类型数组为char sstr指向该数组的第一个元素。

由于复合文字不是只读的(没有const 限定符),您可以修改str 指向的对象。 .

您应该注意的另一个区别是字符串文字 "String!"第一个具有静态存储持续时间,而复合文字 (char []){"String!"}在第二个中,只有当它发生在函数体之外时才具有静态存储持续时间;否则,它具有与封闭 block 关联的自动存储持续时间。

来自 n1570 6.5.2.5(复合文字)p12:

12 EXAMPLE 5 The following three expressions have different meanings:

"/tmp/fileXXXXXX"
(char []){"/tmp/fileXXXXXX"}
(const char []){"/tmp/fileXXXXXX"}

The first always has static storage duration and has type array of char, but need not be modifiable; the last two have automatic storage duration when they occur within the body of a function, and the first of these two is modifiable.

关于c - 这两个初始化是等价的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73001910/

相关文章:

c - 需要一些帮助来理解 C 中的指针和内存

c - 结构与 ptr 数组嵌套结构分配和内存分配

c - 如何在不进行类型转换的情况下通过乘法避免整数溢出?

c - 找到= strchr(st, '\n');替换为 *find = '\0' ;

使用 C 计算行数

c++ - 在函数中创建值,然后将指针保存在全局指针数组中的值上

c - 使用 fscanf 读取项目

ios - 快速字符串操作

javascript - 格式化一些数据以作为多连字符字符串名称传递

R strip拆分数据框中的一列