access element of struct passed into a void* pointer

前端 未结 2 623
陌清茗
陌清茗 2020-12-19 18:47

I\'m working with a binary search tree data structure to sort a series of structs with the type definitions:

typedef struct {
    char c;
    int index;
} da         


        
2条回答
  •  忘掉有多难
    2020-12-19 18:52

    Sure it's possible, you'd cast key as type *data_t. (As long as that's really what key points to!)

    key                     /* argument of type void* */
    (data_t*)key            /* cast as type data_t*   */
    ((data_t*)key)->index   /* dereferenced */
    

    Here is a simple example:

    #include 
    #include 
    
    typedef struct {
        char    c;
        int     index;
    } data_t;
    
    typedef struct node {
        void    *data;
        struct node *left;
        struct node *right;
    } node_t;
    
    static int cmp(void *lhs, void *rhs)
    {
        return ((data_t *)lhs)->index - ((data_t *)rhs)->index;
    }
    
    int main(void)
    {
        data_t d0;
        data_t d1;
    
        d0.c     = 'A';
        d0.index = 1;
        d1.c     = 'B';
        d1.index = 2;
    
        printf("d0 < d1? %s\n", (cmp((void *)&d0, (void *)&d1) < 0 ? "yes" : "no"));
        printf("d1 < d0? %s\n", (cmp((void *)&d1, (void *)&d0) < 0 ? "yes" : "no"));
    
        return EXIT_SUCCESS;
    }
    

提交回复
热议问题