【发布时间】:2010-11-08 19:11:12
【问题描述】:
为什么我可以这样做
char identifier[4] = {'A', 'B', 'C', 'D'};
而不是
char identifier[4];
&identifier = {'A', 'B', 'C', 'D'}; // syntax error : '{'
?
为什么我可以这样做
char identifier[4] = "ABCD"; // ABCD\0, aren't that 5 characters??
而不是
char identifier[4];
&identifier = "ABCD"; // 'char (*)[4]' differs in levels of indirection from 'char [5]'
?
这是在开玩笑吗??
【问题讨论】:
-
如果您需要将声明与赋值分开,您始终可以这样做:
char identifier[4]; sprintf(identifier, "ABCD");。只需确保分配的字符串适合分配的数组或使用安全版本,sprintf_s。 -
好的,谢谢!这行得通,但为什么我需要一个像这样简单的函数......
-
@Jaime:在这种情况下,您不认为 sprintf() 可能是一把大锤吗? memcpy() 就足够了 并且 解决了您提出 sprintf_s() 的问题。
-
@Midas:因为数组不是 C 中的数据类型,所以它是同一类型的对象的连续序列。数组的行为不像对象。
-
@Midas:克利福德是正确的。您不需要在
sprintf中使用字符串格式修饰符。你应该使用char identifier[4]; memcpy(identifier, "ABCD", 4)。