从 char* 复制到 char[]

发布于 2024-12-18 02:25:07 字数 193 浏览 1 评论 0 原文

除了使用 strcpy 之外,还有什么方法可以从 char* 复制到 char[] 吗? 我尝试过这个但不起作用.. for ex

char* t1 = "hello";
char t2[6];
t2 = t1;

它没有编译..说'char*'到 char[6] 的赋值类型不兼容

谢谢

is there any way to copy from char* to char[] other than using strcpy?
I tried this and does not work..
for ex

char* t1 = "hello";
char t2[6];
t2 = t1;

It is not compiling.. saying that incompatible types of assignment of 'char*' to char[6]

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

情绪操控生活 2024-12-25 02:25:07

使用 strncpy

strncpy(t2, t1, 6);

Use strncpy:

strncpy(t2, t1, 6);
脱离于你 2024-12-25 02:25:07

首先,你不能做 char* t1 = "hello";;仅仅因为字符串文字是常量,任何通过 t1 修改它们的尝试都将导致未定义的行为。

由于 C++ 没有从常量字符指针到字符数组的赋值运算符,因此您必须手动复制内存。 memcpy, memmovestrcpystrncpy 是您的标准选项,您始终可以编写自己的选项(我不建议您这样做)。

First thing first - you cannot do char* t1 = "hello";; Simply because string literals are constant, and any attempt to modify them trough t1 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 or strncpy are your standard options, and you can always write your own (which I don't recommend you doing).

如痴如狂 2024-12-25 02:25:07

您需要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.

剑心龙吟 2024-12-25 02:25:07

为了超级安全,您应该使用 strncpy 进行复制,并使用 strnlen 获取字符串的长度,以某个 MAX_LENGTH 为界,以防止缓冲区溢出。

char t2[MAX_LENGTH];
strncpy(t2, t1, strnlen(t1, MAX_LENGTH))

请记住,t1 只是一个指针 - 一个指向内存中某个位置的数字,而不是实际的字符串。您不能使用赋值运算符来复制它。

To be supersafe, you should use strncpy to copy and strnlen to get the length of the string, bounded by some MAX_LENGTH to protect from buffer overflow.

char t2[MAX_LENGTH];
strncpy(t2, t1, strnlen(t1, MAX_LENGTH))

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.

夢归不見 2024-12-25 02:25:07

在 C++ 中,您还可以使用copy

#include <algorithm>

std::copy(t1, t1 + 6, t2);

In C++, you can also use copy:

#include <algorithm>

std::copy(t1, t1 + 6, t2);
大海や 2024-12-25 02:25:07
char* t1 = "hello";
char t2[6];
memcpy(t2, t1, 6);

或者

char* t1 = "hello";
char t2[6] = { t1[0], t1[1], t1[2], t1[3], t1[4], t1[5] };
char* t1 = "hello";
char t2[6];
memcpy(t2, t1, 6);

Or

char* t1 = "hello";
char t2[6] = { t1[0], t1[1], t1[2], t1[3], t1[4], t1[5] };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文