在下面的代码示例中,动态分配整数的内存并将值复制到新的内存位置。
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::string
和 std::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/