【问题标题】:Having trouble getting the value when converting a void pointer to a struct将 void 指针转换为结构时无法获取值
【发布时间】:2026-01-09 07:40:02
【问题描述】:

我传入了一个 void 指针,该指针从结构转换为函数 topTwo。当我将其转换回来并尝试从结构中获取数据时,我得到了地址。我究竟做错了什么? 在这个函数中,我试图让 localStruct->number 返回 1,而不是返回地址。

 void  *topTwo(void *p)
 {
  struct Variables * localStruct;
  localStruct= (struct Variables *) p;
  cout<<localStruct->number<<endl;
  int  z = long(localStruct->number);
  cout<<z<<endl;
}

这是结构

struct Variables{
 int largestNum;
 int secondLargestNum;
 int number;
};

这是传入数据的主要函数。

int main() 
{
    Variables *vars;
    vars= new struct Variables();
    vars->largestNum=0;
    vars->secondLargestNum=0;
    vars->number=0;
    pthread_t  tid[5];
    for(int  i=0; i<5; i++)
    {                                   
       vars->number=i;
       cout<<vars->number<<endl;                                               
       void * sVoid;
       sVoid = (void *) &vars;
       pthread_create(&tid[i], NULL, topTwo,(void *) sVoid);
       pthread_join(tid[i], NULL);
    }
 }

【问题讨论】:

    标签: c++ struct operating-system void-pointers


    【解决方案1】:

    变化:

    sVoid = (void *) &vars;  // this is a `struct Variables**`
    

    到:

    sVoid = (void *) vars;
    

    【讨论】:

    • 谢谢,由于某种原因,我要使用的示例中包含 &
    • 演员阵容真的不需要。