单词“你好” C 中字符数组的赋值
在 C 中,这是合法的并且可以编译:
char names[5] = "Hello";
但这一个不是:
char names[5];
names = "Hello";
How do I put assignment in array of strings word "Hello" ?我可以在没有 strcpy
的情况下做到这一点吗?
In C that's legal and will compile:
char names[5] = "Hello";
but this one is not:
char names[5];
names = "Hello";
How do I put assignment in array of characters word "Hello" ? Can I do that without strcpy
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能。在 C 中,数组不是左值,因此您无法为其赋值。
唯一的方法是:
memcpy
或strcpy
)You cannot. In C an array is not an lvalue so you can't assign to it.
The only ways to do it:
memcpy
orstrcpy
for example)由于终止空字节,您的
names
字符串应至少有 6 个(而不是 5)个字符:使用
strcpy
或等效代码,例如以及最新版本
gcc
(即 4.6),当要求足够的优化(-O2
)时,会将strcpy(names,"Hello");
优化为等价的上面的代码。Your
names
string should have at least 6 (not 5) characters, because of the terminating null byte:Either with
strcpy
or with the equivalent code, e.g.And a recent version of
gcc
(i.e. 4.6), when asked for enough optimization (-O2
), would optimizestrcpy(names,"Hello");
into equivalent of above code.你的代码将会有问题。 C 字符串末尾有一个额外的空字符。 “你好”需要 6 个字节。我相信你的字符串“Hello”将在第一个示例中变成“Hell”。
Your code is going to have problems. C strings have an extra null character at the end. "Hello" requires 6 bytes. I believe your string "Hello" is going to turn into "Hell" in the first example.