This question already has answers here:
Closed 7 months ago.
How to access members through a void pointer
(4个答案)
当将void*指针传递到结构的基址时,我无法访问结构的成员有人能给我一个解决办法或解释一下这个错误吗?现在我收到消息“goroutines.c:142:31:错误:请求成员'qtail'的内容不是结构或联合”
    //Channel struct
struct channel{
    int magicnumber;
    int length;
    int capacity;

    struct gcb* qhead; //head of the queue
    struct gcb* qtail; //tail of the queue
};


void *makeChannel(int dataLength, int capacity){
  if( dataLength <= 0){
    panic( "data length must be greater than zero" );
  }
  if( capacity < 0){
    panic( "capacity must be non-negative" );
  }
  struct channel* ch = (struct channel* )malloc( dataLength * capacity );
  ch->magicnumber = 0x1ca91ac3;
  ch->capacity = capacity;
  ch->length = 0;
  return ch;
}

void sendChannel(void *channel, void *fetchAddress){
  if( capChannel( channel ) == lenChannel( channel ) ){

    (struct channel* )&channel->qtail->next = head;
  }
}

最佳答案

取消引用指针是无效的。去引用基本上是从基指针开始的数值偏移如果编译器不知道指针的类型,它如何知道偏移量,也无法确定成员引用是否实际有效。
在你的函数中,它是cast,看起来好像有一个杂散的void*

void sendChannel(void *channel, void *fetchAddress)
{
    struct channel *chan = (struct channel *)channel;

    if( capChannel( chan ) == lenChannel( chan ) )
    {
        chan->qtail->next = head;
    }
}

但你的角色不适用于任何事情我更喜欢将强制转换显式化,方法是将它赋给一个临时局部变量我觉得这使生成的代码更可读,因为这里和那里都没有类型转换。

关于c - 如何从指针访问结构成员,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55487055/

10-15 00:35
查看更多