0

私の問題は、realloc() を呼び出すときの行にありますが、最初の "Elemento" #include #include using namespace std; で動作します。

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

4

2 に答える 2

0

問題の根源は、手動のメモリ管理です。これは 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;

これを行うと、プログラムははるかに簡単になり、エラーが発生しにくくなります。

于 2013-04-01T06:03:05.900 に答える
0

このコードでは

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

スタック上に作成された dic を返すのはなぜですか。ヒープ上に作成してから返す必要があります。

そうしないと、オブジェクトがスコープ外になると破棄されます。

于 2013-04-01T06:15:33.200 に答える