簡體   English   中英

帶矢量的結構分段故障

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM