2013-04-01 38 views
0

我的问题是在我调用realloc()的行中,但与第一个“Elemento” #include #include using namespace std;在其他结构中的数组结构的realloc

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; 
} 

这里是主要的():

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

我有几天的时间并没有什么,我需要一些帮助.. TY

回答

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; 

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

+0

正确的..但很容易与STL,我想的其他解决方案,而STL或者是仅含有C –

+0

@RobertoCuadros:让你的心,你想一个C++程序ORA C程序?你不能告诉我们你想用C++编写一个程序,然后期望在C中得到一个解决方案。你已经在使用'std :: string'所以我不明白为什么使用'std :: vector'应该是一个问题。 –

+0

ty非常多,ü对,我只是尝试TAD的..我将字符串更改为char *和字符串* char **,最后是好的 –

0

在这段代码

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

为什么要退这是在栈上创建DIC。你应该在堆上创建它,然后返回。

否则当物体超出范围时将被销毁。

+0

该对象是由值返回,所以没有问题。 –