[英]Struct in Struct with vectors Segmentation Fault
我有两个结构ITEM和TABLE,其中一个包含另一个结构,即TABLE包含许多ITEMS。 我使用此代码来创建结构以及表和项目。
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
struct ITEM {
std::string itemTitle;
};
struct TABLE {
std::string tableName;
int num;
ITEM* items;
};
TABLE setTABLE(std::string, int num) {
struct ITEM* item = (struct ITEM*) malloc(sizeof(struct ITEM) * num);
TABLE table = {tableName, num, item};
return table;
}
int main() {
std::vector<TABLE> tables;
tables.push_back(setTABLE("TEST", 3));
tables[0].items[0].itemTitle = "TestItem";
std::cout << tables[0].items[0].itemTitle << "\n";
return 0;
}
我想将ITEM的itemTitle设置在0位置,但是当我得到结果时我得到了
Segmentation fault: 11
我猜malloc还不够呢? 或者我的代码构造首先被误解了? 我想要实现的是构建一个自定义表结构。
malloc()
分配内存,而new
分配内存并初始化(例如调用对象的构造函数)。 当正在使用malloc()
, items
是指向已分配但未初始化的内存的指针,可在以下位置访问:
tables[0].items[0].itemTitle = "TestItem";
导致分段错误。 但是,不要使用new
只需使用std::vector<ITEM>
。 初始大小不是必需的,但如果需要可以提供,并且使用n
默认元素构造vector
:
struct Table
{
Table(std::string const& aName, const size_t a_num) :
tableName(aName), items(a_num) {}
std::string tableName;
std::vector<Item> items;
};
注意num
不再需要,因为可以使用items.size()
并且不使用全部大写,因为这些通常用于宏。
你正在返回在堆栈上创建的变量table
- 你需要首先使用malloc
内存table
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.