2012-11-07 144 views
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

谢谢!

+0

1)在struct中创建指针:就像你做的一样。 2)在使用它之前,确保*每个*指针实际上*指向某个东西。确保你已经分配了*分配的每个对象 - 并正确指定了指针! – paulsm4

回答

2

我可能会得到负repped agian为试图回答一个C的问题,但在这里不用什么

你尝试摆脱&的?

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

我会对你轻松,但最有可能的情况是这些指针尚未初始化。尽管如此,我们不能肯定地说,所以我没有-1 –

+0

@EdS。这就是我一开始要说的,但后来我更仔细地阅读了这个问题,而且似乎他已经能够使用这两个值了。 –

+0

那么,获取未初始化指针的地址不会导致段错误并且完全有效。指针本身有一个有效的地址。解引用无效指针可能会导致段错误,所以这是我的猜测。 –

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 */ 

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