相关疑难解决方法(0)

当malloc()使用相同的结构时,如何在结构中使用C++字符串?

我编写了以下示例程序,但它与segfault崩溃.问题似乎是在结构中使用mallocstd::strings.

#include <iostream>
#include <string>
#include <cstdlib>

struct example {
 std::string data;
};

int main() {
 example *ex = (example *)malloc(sizeof(*ex));
 ex->data = "hello world";
 std::cout << ex->data << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何让它发挥作用.任何想法,如果它甚至可以使用malloc()std::strings?

谢谢,Boda Cydo.

c++ string malloc struct

16
推荐指数
2
解决办法
1万
查看次数

标签 统计

c++ ×1

malloc ×1

string ×1

struct ×1