简体   繁体   中英

Casting a void pointer in a struct to a struct to access members

I'm writing a function to remove a block of data from a dynamic array of blocks Here I have found the specific block I want to remove, the pointer to it is startPos And startPos is a struct of the following type.

typedef struct
{
    void *last; 
    int8_t pos; 
    void *data; 
    void *next; 
} DArrBlock; 

last and next are classic linked list pointers to other DArrBlocks. To remove the specific block, I thought the easiest way would be like this:

startPos->last->next = startPos->next; 
startPos->next->last = startPos->last; 
free(startPos); 

Obviously this doesn't work since next and last are void pointers, and therefore the compiler has no way of knowing that they have the fields I'm trying to access. So you want to cast them to *DArrBlock. But how do you do this? I thought this would be the way

startPos->(*DArrBlock)last->next = startPos->next; 
startPos->(*DArrBlock)next->last = startPos->last; 

but this gives the error "base.c:106:15: error: expected identifier before '(' token"

So how do you cast a void pointer field of a structure to a pointer to a structure?

I know it can be done with an intermediate variable like this

prev = startPos->last; 
next = startPos->next; 
prev->next = startPos->next; 
next->last = startPos->last; 

but I imagine that this slows things down quite a bit since you store two new pointers.

You don't have to use void pointers in the first place, just name your struct and declare last and next as pointers to your struct:

typedef struct DArrBlock
{
    struct DArrBlock *last; 
    int8_t pos; 
    void *data; 
    struct DArrBlock *next; 
} DArrBlock;

If you use void pointers, you have to cast properly:

((DArrBlock*)startPos->next)->last = ...

As for the overhead when using a temporary variable - any decent compiler would optimize that away (when not compiling without optimizations)

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.

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