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