通用void *说明成员'word'的请求不是结构或联合

问题描述

我是C语言中void指针的新手。不幸的是,当我尝试在结构中调用变量时,它引发了以下错误

[Error] request for member 'word' in something not a structure or union

给我的印象是,要做的就是创建一个void * var,然后可以将其用于引用任何数据或将其设置为任何值

    #include <stdlib.h>

struct node{
    void* listHeader; 
    struct node *next; 
}; 

struct otherNode {
   /*The word it stores*/ 
   char* word; 

};

void Method(struct node *header);

int main(){
     struct node *header = malloc(sizeof(struct node)); 
     Method(header); 
     return 0; 
}
void Method(struct node *header){
    (struct otherNode)(header->listHeader).word = "ties";
    
}

任何帮助将不胜感激!!谢谢您的时间!

解决方法

此行的两个问题:

(struct otherNode)(header-> listHeader).word =“ tie”;

  1. 操作员优先。 .优先于投射。

  2. 您正在尝试将(void *)强制转换为(struct otherNode)。您实际上无法做到这一点,可以将其转换为指向该结构的指针,如下所示:

((struct otherNode*)header->listHeader)->word = "ties";

这将使您的代码编译,但不会成功运行,因为您尚未将header->listHeader设置为指向任何地方(header->listHeader = malloc(sizeof(struct otherNode));吗?),因此您正在写到不应该使用的内存区域


资源:

https://en.cppreference.com/w/c/language/operator_precedence