c - 如何从指针访问结构成员

标签 c

<分区>

在将 void* 指针传递给该结构的基地址时,我无法访问该结构的成员。谁能提供解决方案或向我解释错误?现在我收到消息“goroutines.c:142:31: error: request for member ‘qtail’ in something not a structure or union”

    //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;
  }
}

最佳答案

取消引用 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/

相关文章:

c - Fscanf 奇怪地递增文件位置指针

c++ - 将 C++ vector 转换为 C

c - 从不同文件访问静态数组的 'strdup'

python - 如何将带有 char** argv 的 C 函数输入转换为 python?

c++ - 如何比较 C++ 中的内存位?

c++ - c/c++ Linux 相当于 "bool DllMain()"- 但我需要将失败返回给 dlopen()

c - 将 float 分配给整数时无限循环

c - 使用 fgets() 时将值放入链表 header 中

检查文件是否只有 C 语言的字母字符

C/C++ - 了解音频插值代码