简体   繁体   中英

Having trouble getting the value when converting a void pointer to a struct

I am passing in a void pointer that was converted from a struct into a function topTwo. When I cast it back and try to get data from the struct I get the address instead. What am I doing wrong? In this function I am trying to get localStruct->number to return 1 and instead it is returning the address.

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

Here is the struct

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

Here is the main function that passes in the data.

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

Change:

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

to:

sVoid = (void *) vars;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM