c++ - 结构中的字符串

标签 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;
}

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

最佳答案

C++ 不是 C。

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

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

node* p = new node();

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

node p;

C++ 不是 C。

关于c++ - 结构中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31269728/

相关文章:

c++ - 删除额外的括号

javascript - 如何设置特定 xml 字符串节点的值?

c# - 在 C# 中向字符串添加空格

c - 在结构中引用结构,在函数中引用结构

c++ - 错误 : invalid initialization for struct in C++

c - 在这种情况下如何正确使用 struct

C++ 破坏表达式中的临时对象

c++ - 有人可以解释一下这行代码吗

c# - 开关盒编程实践

c++ - 指向函数赋值的指针