从 char* 复制到 char[]
除了使用 strcpy 之外,还有什么方法可以从 char* 复制到 char[] 吗? 我尝试过这个但不起作用.. for ex
char* t1 = "hello";
char t2[6];
t2 = t1;
它没有编译..说'char*'到 char[6] 的赋值类型不兼容
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用 strncpy:
Use strncpy:
首先,你不能做
char* t1 = "hello";
;仅仅因为字符串文字是常量,任何通过t1
修改它们的尝试都将导致未定义的行为。由于 C++ 没有从常量字符指针到字符数组的赋值运算符,因此您必须手动复制内存。
memcpy
,memmove
,strcpy
或strncpy
是您的标准选项,您始终可以编写自己的选项(我不建议您这样做)。First thing first - you cannot do
char* t1 = "hello";
; Simply because string literals are constant, and any attempt to modify them trought1
will result in undefined behavior.Since C++ doesn't have assignment operators from constant character pointer to character array, you have to copy memory manually.
memcpy
,memmove
,strcpy
orstrncpy
are your standard options, and you can always write your own (which I don't recommend you doing).您需要
strcpy
。 C++(C)中的数组有一个指向第一项(在本例中为字符)的指针。所以
strcpy(t2, t1)
就可以了。另外 - 出于迂腐,你需要
const char * const t1 = "hello"
- 但标准在这个问题上给予了很大的宽容。You need
strcpy
. Arrays in C++ (an C) have a pointer to the first item (character in this case).So
strcpy(t2, t1)
will do the trick.Also - being perdantic you need
const char * const t1 = "hello"
- but the standard gives a lot of tolerance on that subject.为了超级安全,您应该使用
strncpy
进行复制,并使用strnlen
获取字符串的长度,以某个 MAX_LENGTH 为界,以防止缓冲区溢出。请记住,
t1
只是一个指针 - 一个指向内存中某个位置的数字,而不是实际的字符串。您不能使用赋值运算符来复制它。To be supersafe, you should use
strncpy
to copy andstrnlen
to get the length of the string, bounded by some MAX_LENGTH to protect from buffer overflow.Remember, that
t1
is only a pointer - a number that points you to some place in memory, not an actual string. You can't copy it using assignment operator.在 C++ 中,您还可以使用
copy
:In C++, you can also use
copy
:或者
Or