简体   繁体   English

从结构体中的指针访问结构体的值

[英]Access values of structs from a pointer in a struct

I'm going to try and keep this as brief as possible. 我将尝试使其尽可能简短。 So I have two structs: 所以我有两个结构:

typedef struct someStruct named;
struct someStruct {
    void *key;                  
    void *value;                    
};
typedef struct anotherStruct namedToo;
struct anotherStruct {
    named **table;          
    unsigned int size;          
};

Okay great, now ingore any possible mistakes above, this is uneditable code. 好的,很好,现在请记住上面的所有可能的错误,这是不可编辑的代码。

Now I have two methods: 现在,我有两种方法:

namedToo *init(float ignoreThis) {
    namedToo *temp;
    temp = malloc(sizeof(namedToo)); //some memory for the second struct
    temp->table = malloc(sizeof(named)*100); //lets say this 100 is for 100 buckets/cells/named elements
    return temp;

Method 2: 方法2:

int insert(namedToo *temp, void* key, void* value) {
     temp->table[0]->key = key; //My problem, I need to access the value and key inside named from the pointer inside namedToo. How can I do this?
}

The comment has my problem : My problem, I need to access the value and key inside named from the pointer inside namedToo. 评论有我的问题:我的问题是,我需要从namedToo内部的指针访问named内部的值和键。 How can I do this? 我怎样才能做到这一点? I would need to change and grab value/key on their own from time to time. 我需要不时自行更改和获取值/密钥。

The declaration named **table; named **table;的声明named **table; says table is pointer to a pointer to named , or alternately an array of pointer to named . table是指向named指针的指针,或者是指向named的指针的数组。 The latter is you seem to intend. 后者似乎是您打算的。

This allocation: 此分配:

temp->table = malloc(sizeof(named)*100); 

Allocates space for 100 named , but what you need are 100 named * , and each of those must point to a named . 为100个named空间分配空间,但是您需要100个named * ,并且每个空间必须指向一个named Given the definition of named this is likely enough space, however at this point you have an array of uninitialized pointers. 给定named的定义,这可能有足够的空间,但是,此时您有一个未初始化的指针数组。 Attempting to access them results in undefined behavior , which in this case manifests as a core dump. 尝试访问它们会导致未定义的行为 ,在这种情况下,这表现为核心转储。

You need to allocate space for an array of pointers, then initialize each of those to a single dynamically allocated instance of named . 您需要为一个指针数组分配空间,然后将每个指针初始化为一个动态分配的named实例。 So you should be allocating space like this: 因此,您应该像这样分配空间:

int i;
temp->table = malloc(sizeof(named *)*100);
for (i=0; i<100; i++) {
    temp->table[i] = malloc(sizeof(named));
}

Then your insert method should work properly. 然后,您的insert方法应该可以正常工作。

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

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