如何复制包含“\0”字符的数据 [英] How could I copy data that contain '\0' character
问题描述
我正在尝试复制\0的数据。我使用C ++。
当研究结果是否定的,我决定写我自己的命令来将数据从一个char *复制到另一个char *。但它不返回想要的结果!
我的尝试如下:
I'm trying to copy data that conatin '\0'. I'm using C++ . When the result of the research was negative, I decide to write my own fonction to copy data from one char* to another char*. But it doesn't return the wanted result ! My attempt is the following :
#include <iostream>
char* my_strcpy( char* arr_out, char* arr_in, int bloc )
{
char* pc= arr_out;
for(size_t i=0;i<bloc;++i)
{
*arr_out++ = *arr_in++ ;
}
*arr_out = '\0';
return pc;
}
int main()
{
char * out= new char[20];
my_strcpy(out,"12345aa\0aaaaa AA",20);
std::cout<<"output data: "<< out << std::endl;
std::cout<< "the length of my output data: " << strlen(out)<<std::endl;
system("pause");
return 0;
}
结果如下:
the result is here:
我不明白我的代码有什么问题。
I don't understand what is wrong with my code.
感谢您提前寻求协助。
推荐答案
当你写 char *
到 cout
时,c $ c> my_strcpy 或calc的长度与 strlen
他们停止在 \0
。顺便说一下,您可以使用 memcpy
复制 char
的块,而不管 \ 0
。
Your my_strcpy
is working fine, when you write a char*
to cout
or calc it's length with strlen
they stop at \0
as per C string behaviour. By the way, you can use memcpy
to copy a block of char
regardless of \0
.
这篇关于如何复制包含“\0”字符的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!