在将void指针转换为struct时无法获取值

时间:2012-04-25 00:46:03

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

我传入一个从结构转换为函数topTwo的void指针。当我把它强制转换并尝试从结构中获取数据时,我得到了地址。我究竟做错了什么? 在这个函数中,我试图让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);
    }
 }

1 个答案:

答案 0 :(得分:3)

变化:

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

为:

sVoid = (void *) vars;