结构中的字符串

String in struct

本文关键字:字符串 结构      更新时间:2023-10-16
#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;
}

上面的代码产生了一个运行时错误。该结构适用于int,但当我尝试使用字符串作为其成员变量时,会发生错误。它还提供了代码厨师端的运行时错误。

C++不是C.

您不应该从bits文件夹中#include任何内容。

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

node* p = new node();

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

node p;

C++不是C.

不要使用malloc:不会调用std::string的构造函数,因此创建的对象将处于未定义状态。

请改用new。然后,C++运行时将调用std::string成员的默认构造函数。不要忘记将newdelete进行匹配。

您忘记声明str。此外,不要使用new(当然而不是malloc!!(,除非您必须(读取:从不(:

#include <iostream>
#include <string>
using namespace std;
struct node {
    std::string a;
};
int main()
{
    std::string str;
    cout << str << endl;
    node p;
    p.a = "a";
    cout << p.a;
}