【发布时间】:2014-11-03 09:47:01
【问题描述】:
我被memcpy从一个字符串到一个cstring,以及C++中的字符串结构弄糊涂了,即在下面的代码中:
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
int main()
{
string str="hahah";
cout<<"the length of the coverted c string is: "<<strlen(str.c_str())<<endl; // 5
char *char1=new char[6];
memcpy(char1, str.c_str(), strlen(str.c_str()));
cout<<char1<<endl;
// (1) output is "hahah", why copying only 5 bytes also produce correct result? Why the last byte default to be \0?
cout<<sizeof(str)<<endl; // (2) why the size of str is8, rather than 6
memcpy(char1, &str, 6);
cout<<char1<<endl; // (3) output is strange. Why ?
return 0;
}
谁能帮我解释一下为什么 (1)、(2) 和 (3) 会在评论中发生?
【问题讨论】:
-
你应该看看这个答案:stackoverflow.com/a/5952598/4182012
标签: c++ string memcpy c-strings