[英]C++ char* array
当我创造类似的东西
char* t = new char[44];
t = strcpy(s,t);
strlen(t);
返回一些错误的结果。 我怎么能改变这个?
strcpy
和strlen
希望在数组中找到特殊字符NUL
或'\\0'
。 未初始化的数组,就像您创建的那样,可能包含任何内容,这意味着当将程序作为源参数传递给strcpy
时,程序的行为是未定义的。
假设目标是将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;
}
但请记住,在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';
}
你想做什么? 你想从s
复制到t
吗? 如果是这样, strcpy
的参数是相反的。
char* t = new char[44]; // allocate a buffer
strcpy(t,s); // populate it
这种C风格的字符串处理是一个红旗,但考虑到这些小信息,我可以说。
此代码可能会有所帮助:
char * strcpy (char * destination, const char * source);
t = strcpy(t, s);
你必须初始化变量t
做这样的事情:
char *t = new char[44];
memset(t, 0, 44);
// strlen(t) = 0
因此描述了 strcpy
函数:
#include <string.h>
char *strcpy(char *dest, const char *src);
strcpy()函数将
src
指向的字符串(包括终止的'\\ 0'字符)复制到dest
指向的数组。
所以,如果你试图填写新分配的数组,你应该这样做:
strcpy(t, s);
不是相反。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.