简体   繁体   English

将结构中的 void 指针转换为结构以访问成员

[英]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.我正在写一个 function 从块的动态数组中删除一个数据块在这里我找到了我要删除的特定块,指向它的指针是 startPos 而 startPos 是以下类型的结构。

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

last and next are classic linked list pointers to other DArrBlocks. last 和 next 是指向其他 DArrBlock 的经典链表指针。 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.显然这不起作用,因为 next 和 last 是 void 指针,因此编译器无法知道它们具有我要访问的字段。 So you want to cast them to *DArrBlock.所以你想将它们强制转换为 *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"但这会给出错误“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?那么如何将结构的 void 指针字段转换为指向结构的指针呢?

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:您不必首先使用 void 指针,只需命名您的结构并将lastnext声明为指向您的结构的指针:

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:如果使用 void 指针,则必须正确转换:

((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)至于使用临时变量时的开销 - 任何体面的编译器都会优化它(当不编译时没有优化)

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

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