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

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.

https://stackoverflow.com/questions/73001910/

相关文章:

python - 如果我更改了类中的函数名称,该函数会发生什么变化?

r - 如何制作渐变彩虹调色板图?

windows - 在 3 个不同的子目录中创建 2 个子目录

java - 如何修复 java.lang.ClassNotFoundException : org

java - 比较不同时区的 ZoneDdateTime

sql - 甲骨文 SQL : SUM in first row with condition

java - Java 17 中的线程安全随机生成器

c++ - 尽管类型删除,是否可以使用静态多态性(模板)?

awk - 在列中找到确切的字符串

c++ - 第二次编译时更改随机生成数字的值