字符串中的memcpy

memcpy from a string

本文关键字:memcpy 字符串      更新时间:2023-10-16

我被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 ?
    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. 你真幸运。默认情况下,它不会初始化为任何内容。但是,您可以使用char* char1 = new char[6]()使其0初始化。

  2. sizeof(str)返回8,因为在您的计算机上string实例的大小是8。它不依赖于str的长度。

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