来自字符串的memcpy

时间:2014-11-03 09:47:02

标签: c++ string memcpy c-strings

我对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)吗?

1 个答案:

答案 0 :(得分:2)

  1. 你很幸运。默认情况下,它不会初始化为任何内容。但是,您可以使用char* char1 = new char[6]()进行0初始化。

  2. sizeof(str)返回8,因为您机器上string实例的大小为8。它不依赖于str

  3. 的长度
  4. 使用memcpy(char1, &str, 6)时,它会复制str的前6个字节,而不是其内容的前6个字节。

相关问题