【问题标题】:memcpy from a string来自字符串的 memcpy
【发布时间】: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) 会在评论中发生?

【问题讨论】:

标签: c++ string memcpy c-strings


【解决方案1】:
  1. 你很幸运。默认情况下它没有初始化为任何东西。但是,您可以使用 char* char1 = new char[6]() 使其初始化为 0。

  2. sizeof(str) 返回 8,因为在您的计算机上 string 实例的大小为 8。与str的长度无关。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-22
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2011-09-11
    相关资源
    最近更新 更多