2011-04-12 108 views
1

當我創造這樣C++的char *數組

char* t = new char[44]; 
t = strcpy(s,t); 

然後strlen(t);返回一些錯誤的結果。我怎麼能改變這個?

+0

您好,АлександрБрус,歡迎來到Code Review。你的問題不是關於工作代碼(如[faq](http://codereview.stackexchange.com/faq)中所述),所以我將它遷移到了stackoverflow。 – 2011-04-12 16:50:23

回答

6

strcpystrlen都希望在數組中找到特殊字符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); 

不是相反:

所以,如果你正試圖填補你的新分配的數組,你應該做的。