简体   繁体   English

如何在结构内创建指针

[英]How to create a pointer inside a struct

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 . 我如何获取tabela->indice[0].bucket地址并将其关联到tabela->indice[2].bucket

Thanks! 谢谢!

I'm probably going to get neg repped agian for attempting to answer ac question, but here goes nothing 我可能会因为尝试回答ac问题而遭到拒绝。

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. 对于我而言,很难弄清您实际上在尝试完成什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM