2

我有以下结构:

typedef struct bucket {
    unsigned int contador; 
    unsigned int * valor;
} Bucket;

typedef struct indice {
    unsigned int bs;            
    unsigned int valor;      
    unsigned int capacidade; 
    Bucket * bucket;
} Indice;

typedef struct tabela {
    unsigned int bs; 
    Indice * indice;
} Tabela;

我想做这样的事情:

tabela->indice[2].bucket = &tabela->indice[0].bucket;

但我得到分段错误。

如何获取tabela->indice[0].bucket地址并关联到tabela->indice[2].bucket.

谢谢!

4

2 回答 2

2

我可能会因为试图回答交流问题而被否定,但这里什么都没有

你试过摆脱&吗?

tabela->indice[2].bucket = tabela->indice[0].bucket;
于 2012-11-07T22:52:22.380 回答
2

您必须初始化指针以指向有效的东西。简单地创建结构的实例并不能为您做到这一点。例如:

Tabela t = {};  /* t is a valid, zero-initialized object, but indice is not valid */

t.indice = malloc(sizeof(Indice) * some_count);
/* now t.indice is valid */

for(int i = 0; i < some_count; ++i)
    t.indice[i].bucket = malloc(sizeof(Bucket));

/* now t.indice[0-(some_count-1)].bucket are all valid */

顺便说一句,您的指针副本不正确。

tabela->indice[2].bucket = tabela->indice[0].bucket;
/* assuming indices 0 and 2 are valid, this now works (but leaks memory)
   note that I removed the &.  It is incorrect and produces
   a Bucket** because t.indice[n].bucket is already a pointer */

但是,这会导致内存泄漏。我很难弄清楚你在这里真正想要完成什么。

于 2012-11-07T22:52:31.693 回答