C++ char* array

C++ char* array

本文关键字:array char C++      更新时间:2023-10-16

当我创建像

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

strlen(t);返回一些错误的结果。我怎样才能改变这一切?

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';
}

你想干什么?你想从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指向的字符串(包括结束字符'')复制到dest指向的数组中。

所以,如果你想填充你新分配的数组,你应该这样做:

strcpy(t, s);