type casting integer to void*

user2282725 picture user2282725 · Apr 15, 2013 · Viewed 33.2k times · Source
#include <stdio.h>
void pass(void* );
int main()
{
    int x;
    x = 10;
    pass((void*)x);
    return 0;
}
void pass(void* x)
{
   int y = (int)x;
   printf("%d\n", y);
}


output: 10

my questions from the above code..

  1. what happens when we typecast normal variable to void* or any pointer variable?

  2. We have to pass address of the variable to the function because in function definition argument is pointer variable. But this code pass the normal variable ..

This format is followed in linux pthread programming... I am an entry level C programmer. I am compiling this program in linux gcc compiler..

Answer

Some programmer dude picture Some programmer dude · Apr 15, 2013

I'm only guessing here, but I think what you are supposed to do is actually pass the address of the variable to the function. You use the address-of operator & to do that

int x = 10;
void *pointer = &x;

And in the function you get the value of the pointer by using the dereference operator *:

int y = *((int *) pointer);