1
A
回答
6
strcpy
和strlen
都希望在数组中找到特殊字符NUL
或。一个未初始化的数组,作为您创建的数组,可能包含任何内容,这意味着程序的行为在作为源参数传递给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';
}
1
此代码可能会有所帮助:
char * strcpy (char * destination, const char * source);
t = strcpy(t, s);
0
你必须初始化变量t
做这样的事情:
char *t = new char[44];
memset(t, 0, 44);
// strlen(t) = 0
+3
或者使用'char * t = new char [44]();',您可以摆脱memset。 – 2011-04-12 17:15:45
2
你到底想干什么?你想从s
复制到t
?如果是这样,strcpy
的参数是相反的。
char* t = new char[44]; // allocate a buffer
strcpy(t,s); // populate it
这样的C风格的字符串处理是一个红旗,但这就是我可以说给这个小的信息。
0
的strcpy
功能is described从而:
#include <string.h>
char *strcpy(char *dest, const char *src);
的的strcpy()函数将串通过
src
指向(包括终止 '\ 0' 字符)到阵列指向dest
。各地strcpy(t, s);
不是相反:
所以,如果你正试图填补你的新分配的数组,你应该做的。
相关问题
- 1. C++ - char数组
- 2. C/C++ enum和char *数组
- 3. C中的char数组?
- 4. 数组的Int和* Char - C++
- 5. C中的char *数组
- 6. char数组中的Turbo C
- 7. C++ Arduino将char *传递给char数组*
- 8. C++转换2维char数组const char **
- 9. 的sizeof用C的char *数组/ C++
- 10. 用char数组填充char数组(char数组到int数组)
- 11. 用char *增加数组* [C++]
- 12. C++ char数组范围
- 13. C-声明char数组
- 14. C++流入char数组?
- 15. C - 在一个2d char *数组中存储多个char数组
- 16. 使用Java char数组处理C char数组
- 17. c char字符数组v C案例的char *初始化
- 18. C++如何使用find函数查找char数组中的char?
- 19. BMP char数组到文件C/C++
- 20. 使用char数组的C++内存池
- 21. 在目标c中的char *数组
- 22. 在c#中的char []数组相当于#
- 23. 的char *编组的C#
- 24. 在C函数中返回char数组
- 25. C++将char数组传递给函数
- 26. C++ char const char *
- 27. 从char数组解析C++中的char指针
- 28. 如何将char/int添加到C中的char数组?
- 29. 将char添加到C中的char数组中
- 30. 在C++中查找char *数组中的char *元素
您好,АлександрБрус,欢迎来到Code Review。你的问题不是关于工作代码(如[faq](http://codereview.stackexchange.com/faq)中所述),所以我将它迁移到了stackoverflow。 – 2011-04-12 16:50:23