C++ char* 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5638831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ char* array
提问by Александр Брус
When I create something like
当我创建类似
char* t = new char[44];
t = strcpy(s,t);
then strlen(t);
return some wrong results. how I can change this?
然后strlen(t);
返回一些错误的结果。我怎么能改变这个?
回答by Cubbi
Both strcpy
and strlen
expect to find the special character NUL
or '\0'
in the array. An uninitialized array, as the one you've created, may contain anything at all, which means the behavior of your program is undefined when it is passed to strcpy
as the source argument.
双方strcpy
并strlen
期望找到的特殊字符NUL
或'\0'
在数组中。一个未初始化的数组,就像您创建的数组一样,可能包含任何内容,这意味着当它strcpy
作为源参数传递给您的程序时,它的行为是未定义的。
Assuming the goal was to copy s
into t
, to make the program behave as expected, try this:
假设目标是复制s
到t
,以使程序按预期运行,请尝试以下操作:
#include <iostream>
#include <cstring>
int main()
{
const char* s = "test string";
char* t = new char[44];
// std::strcpy(t, s); // t is the destination, s is the source!
std::strncpy(t, s, 44); // you know the size of the target, use it
std::cout << "length of the C-string in t is " << std::strlen(t) << '\n';
delete[] t;
}
But keep in mind that in C++, strings are handled as objects of type std::string
.
但请记住,在 C++ 中,字符串作为 类型的对象进行处理std::string
。
#include <iostream>
#include <string>
int main()
{
const std::string s = "test string";
std::string t = s;
std::cout << "length of the string in t is " << t.size() << '\n';
}
回答by Potatoswatter
What are you trying to do? Do you want to copy from s
to t
? If so, the arguments to strcpy
are reversed.
你想做什么?您要从 复制s
到t
吗?如果是,则将 的参数strcpy
颠倒。
char* t = new char[44]; // allocate a buffer
strcpy(t,s); // populate it
Such C-style string processing is a red flag, but that's all I can say given this little information.
这种 C 风格的字符串处理是一个危险信号,但鉴于这些小信息,我只能说这些。
回答by Artem Volkhin
This code might be helpful:
此代码可能会有所帮助:
char * strcpy (char * destination, const char * source);
t = strcpy(t, s);
回答by Juliano
You have to initialize the variable t
你必须初始化变量 t
Do something like this:
做这样的事情:
char *t = new char[44];
memset(t, 0, 44);
// strlen(t) = 0
回答by Rob?
The strcpy
function is describedthus:
的strcpy
功能进行说明这样的:
#include <string.h>
char *strcpy(char *dest, const char *src);
The strcpy() function copies the string pointed to by
src
(including the terminating '\0' character) to the array pointed to bydest
.
strcpy() 函数将 指向的字符串
src
(包括终止的 '\0' 字符)复制到 指向的数组中dest
。
So, if you are trying to fill in your newly allocated array, you should be doing:
因此,如果您尝试填充新分配的数组,则应该执行以下操作:
strcpy(t, s);
Not the other way around.
不是反过来。