I have two structs ITEM and TABLE, one of which contains the other one, i.e. TABLE contains many ITEMS. I use this code to create the structs and the table and items with it.
#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;
}
I want to set the itemTitle of the ITEM at position 0, but when I cout the result i get
Segmentation fault: 11
I guess the malloc is not sufficient to this? Or is my code construction misconstrued in the first place? What I wanted to achieve is build a custom table structure.