结构体中的字符串

aks*_*007 1 c++ string struct

#include <bits/stdc++.h>

using namespace std;

struct node
{
    std::string a;
};

int main()
{
    cout << str << endl;
    struct node* p = (struct node*)(malloc(sizeof(struct node)));
    p->a = "a";
    cout << p->a;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码产生运行时错误。该结构适用于整数,但是当我尝试使用字符串作为其成员变量时,会发生错误。它还会在代码cheide上给出运行时错误。

Bat*_*eba 5

不要使用malloc:构造函数用于std::string不会被调用,所以产生将处于不确定状态的对象。

使用new来代替。然后,C++ 运行时将调用该std::string成员的默认构造函数。不要忘记将new与 a匹配delete


Tar*_*ama 5

C ++不是C。

你不应该#includebits文件夹中获取。

您不应该malloc用来分配内存。您应该new改用:

node* p = new node();
Run Code Online (Sandbox Code Playgroud)

或者只是根本不动态分配内存:

node p;
Run Code Online (Sandbox Code Playgroud)

C ++不是C。