1

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?

1 Answers1

2
  1. You are just lucky. It is not initialized to anything by default. However, you can use char* char1 = new char[6]() to make it 0-initialized.

  2. sizeof(str) returns 8 because the size of a string instance is 8 on your machine. It does not depend on the length of str.

  3. When you use memcpy(char1, &str, 6), it copies the first 6 bytes of str, not the first 6 bytes of its content.

kraskevich
  • 18,368
  • 4
  • 33
  • 45