When going through some of the links about void pointers, I have seen two types when setting and getting values from void pointers,
int main() {
int i = 5;
//This is first way.
void *vPtr = (void *) i;
//printing value of *vPtr,
printf("Getting value in first way, %d\n", (int)vPtr);
//This is second way.
*vPtr = &i;
//printing in second way,
printf("Getting value in second way, %d\n", *((int*)vPtr));
}
Both of them will give the same value. Though I had an idea of how second method works, but I am not entirely sure, how first method works. What would be the ideal way when dealing with void pointers among these two?
For first method, this is the code snippet I was referring. Though he was passing long type, I could do the same with int also.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0;t<NUM_THREADS;t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
}