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
s 和 str
指向该数组的第一个元素。
由于复合文字不是只读的(没有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/