I have the following structs:
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;
And I want to do something like this:
tabela->indice[2].bucket = &tabela->indice[0].bucket;
But I get segmentation fault.
How can I get the tabela->indice[0].bucket
address and associate to tabela->indice[2].bucket
.
Thanks!
I'm probably going to get neg repped agian for attempting to answer ac question, but here goes nothing
have you tried getting rid of the &
?
tabela->indice[2].bucket = tabela->indice[0].bucket;
You have to initialize your pointers to point to something valid. Simply creating an instance of your struct does not do that for you. For example:
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 */
By the way, your pointer copy is incorrect.
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 */
However, that results in a memory leak. It's hard for me to figure out what you are actually trying to accomplish here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.