I am confused by memcpy from a string to a cstring, and the string structure in C++, namely, in the following code:
#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;
}
Can any one help me explain why (1), (2) and (3) in the comment in happening?