如何在struct中创建指针

时间:2012-11-07 22:47:20

标签: c data-structures

我有以下结构:

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相关联。

谢谢!

2 个答案:

答案 0 :(得分:2)

我可能会因为尝试回答一个问题而被拒绝回复,但这里什么都没有

你试过摆脱&吗?

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

答案 1 :(得分: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 */

但是,这会导致内存泄漏。我很难弄清楚你在这里想要实现的目标。