c++ - 如何将字符串复制到新分配的内存中?

标签 c++ string dynamic-memory-allocation

在下面的代码示例中,动态分配整数的内存并将值复制到新的内存位置。

main() {
    int* c;
    int name = 809;
    c = new int(name);
    cout<<*c;
}

但是,当我尝试对 char 字符串执行相同操作时,它不起作用。 这是为什么?

int main() {
    char* p;
    char name[] = "HelloWorld";
    p = new char(name);
    cout << p;
}

最佳答案

您的第二个示例不起作用,因为 char 数组与整数变量的工作方式不同。虽然可以通过这种方式构造单个变量,但这不适用于(原始)变量数组。 (正如您所观察到的。)

在 C++ 中,您应该尽量避免处理指针和原始数组。相反,您宁愿使用标准库容器将该字符串复制到动态分配的内存数组中。 std::stringstd::vector<char>在这种情况下特别合适。 (应该首选哪个取决于语义,但可能是 std::string 。)

这是一个例子:

#include <string>
#include <vector>
#include <cstring>
#include <iostream>

int main(){
    char name[] = "Hello World";

    // copy to a std::string
    std::string s(name);
    std::cout << s << '\n';

    // copy to a std::vector<char>
    // using strlen(name)+1 instead of sizeof(name) because of array decay
    // which doesn't occur here, but might be relevant in real world code
    // for further reading: https://stackoverflow.com/q/1461432
    // note that strlen complexity is linear in the length of the string while
    // sizeof is constant (determined at compile time)
    std::vector<char> v(name, name+strlen(name)+1);
    std::cout << &v[0] << '\n';
}

输出是:

$ g++ test.cc && ./a.out
Hello World
Hello World

供引用:

关于c++ - 如何将字符串复制到新分配的内存中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44240777/

相关文章:

c++ - 忽略大小模板的 std::array::iterator

c++ - 如何使用 boost::asio 将 URL 转换为 IP 地址?

javascript - 在js中将嵌套数组转换为JSON字符串?

c - 如何在c中的两个void指针之间交换内存

C++ Virtual Studio Hello World 缺少命令?

c++ - 名称和派生名称类之间的连接(作为模板参数)

java - ArrayList<String> 类型中的方法 add(String) 不适用于参数 (Object)

Java String 与 REGEX 匹配错误

C:包含动态分配成员的结构的范围?

c - 如果 realloc 返回 NULL,我是否必须释放旧内存?