【问题标题】:realloc of array struct in other struct在其他结构中重新分配数组结构
【发布时间】:2013-04-01 05:59:11
【问题描述】:

当我调用 realloc() 时,我的问题就在一行中,但适用于第一个“Elemento” #包括 #包括 使用命名空间标准;

typedef struct{
   string palabra;
   string* significados;
   size_t tam;
} Elemento;

typedef struct{
   Elemento* elementos;
   size_t tam;
} Diccionario;

Diccionario crearDic(){
   Diccionario dic;
   dic.tam = 0;
   return dic;
}

void agregarPalabraDic(Diccionario &dic, string pal, string sig){   
   dic.elementos = (Elemento*)realloc(dic.elementos,(dic.tam+1)*sizeof(Elemento));
   dic.tam++;

   dic.elementos[dic.tam-1].palabra = pal;   
   dic.elementos[dic.tam-1].significados = (string*)malloc(sizeof(string));    
   dic.elementos[dic.tam-1].tam = 1; 
   dic.elementos[dic.tam-1].significados[0] = sig; 
}

这里是 main() :

int main(){
   Diccionario dic = crearDic();
   agregarPalabraDic(dic,"apple","red"); //no problem here
   agregarPalabraDic(dic,"banana","yellow"); //thats the problem
   ...
}

我有好几天都在尝试,但什么都没有,我需要一些帮助.. ty

【问题讨论】:

    标签: c arrays pointers struct realloc


    【解决方案1】:

    问题的根源在于手动内存管理。因为这是 C++,所以你不需要做所有这些。最好的解决方案是替换:

    typedef struct
    {
       std::string palabra;
       std::string* significados;
       size_t tam;
    } Elemento;
    
    typedef struct
    {
       Elemento* elementos;
       size_t tam;
    } Diccionario;
    

    与:

    typedef struct
    {
       std::string palabra;
       std::vector<string>significados;
       size_t tam;
    } Elemento;
    
    typedef struct
    {
       std::vector<Elemento> elementos;
       size_t tam;
    } Diccionario;
    

    一旦你这样做了,你的程序应该会更容易,更不容易出错。

    【讨论】:

    • 对.. 但是使用 STL 很容易,我想要一个没有 STL 或只有 C 的其他解决方案
    • @RobertoCuadros:下定决心,你想要 C++ 程序还是 C 程序?你不能告诉我们你想用 C++ 编写一个程序,然后期望用 C 得到一个解决方案。你已经在使用 std::string 所以我不明白为什么使用 std::vector 应该是一个问题。
    • ty 非常,你对,我只是尝试 TAD 的.. 我将字符串更改为 char* 并将字符串* 更改为 char**,最后没问题
    【解决方案2】:

    在这段代码中

    Diccionario crearDic(){
       Diccionario dic;
       dic.tam = 0;
       return dic;
    }
    

    为什么要返回在堆栈上创建的 dic。你应该在堆上创建它然后返回。

    否则该对象将在超出范围时被销毁。

    【讨论】:

    • 对象是按值返回的,所以没有问题。
    猜你喜欢
    • 1970-01-01
    • 2011-09-04
    • 2014-05-31
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 2021-05-05
    • 2016-02-08
    相关资源
    最近更新 更多