I have problems with pointer in C, this is an thread example in C.
this code was written in "Advanced Linux Programming" book:
void* print_xs (void* unused)
{
while (1)
fputc (‘x’, stderr);
return NULL;
}
and:
int main()
{
pthread_t thread_id;
pthread_create (&thread_id, NULL, &print_xs, NULL);
while (1)
fputc (‘o’, stderr);
return 0;
}
why print_xs
is void*
?
I found an answer, but it wasn't clear enough to me. the answer:
This declares a pointer, but without specifying which data type it is pointing to
Is it related to return value?
also why void* data type is used for "unused" (void* unused)?
I'm not sure about why "&" is used before print_xs in pthread_create? Is it correct to say: pthread_create is in another library and we want to tell it to run pthread_create function but it doesn't know where is this function, so we tell the the address of this function to it.
A void pointer(void* ) is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typcasted to any type.
For example:
int a = 10;
char b = 'x';
void *unused = &a; // void pointer holds address of int 'a'
unused = &b; // void pointer holds address of char 'b'
Yes, void* print_xs()
has the return type of void pointer.
In pthread_create (&thread_id, NULL, &print_xs, NULL);
pthread_create
function passes the address of thread_id
and print_xs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With