结构中的字符串
String in 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;
}
上面的代码产生了一个运行时错误。该结构适用于int,但当我尝试使用字符串作为其成员变量时,会发生错误。它还提供了代码厨师端的运行时错误。
C++不是C.
您不应该从bits
文件夹中#include
任何内容。
您不应该使用malloc
来分配内存。您应该使用new
:
node* p = new node();
或者根本不动态分配内存:
node p;
C++不是C.
malloc
:不会调用std::string
的构造函数,因此创建的对象将处于未定义状态。
请改用new
。然后,C++运行时将调用std::string
成员的默认构造函数。不要忘记将new
与delete
进行匹配。
您忘记声明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;
}
相关文章:
- C++结构到字符串
- 从字符串中获取结构的大小
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 如何解析表示树状数据结构的字符串
- 如何将字符串与结构(也包括字符串)进行比较?
- 如果结构中的字符串比使用的 p/调用签名长或短,会发生什么情况?
- 在向量 C++14(无限制联合)的结构内的联合中创建和存储字符串
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- 将字符串存储在 constexpr 结构中
- 为什么我的结构在包含字符串时崩溃?
- 如何将字符串字符与结构数组进行比较?
- 无法使用 strcpy 将字符串复制到静态结构成员
- c++ 将函数参数(带有模板变量的结构)转换为函数体内的字符串
- 在 c++ 中使用字符串变量选择静态类结构,而不带对象
- C++使用旧编译器GCC 4.4.0在结构列表中查找字符串
- 具有字符串成员的结构的动态数组
- 如何将文本文件保存到C 中的字符串结构
- C++ 斯特劳斯特鲁普的"std_lib_facilities.h"字符串结构 – 警告:无符号表达式的比较
- C++:字符串结构相等
- 返回字符串结构是否安全