2011-04-12 107 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); 

不是相反:

所以,如果你正试图填补你的新分配的数组,你应该做的。