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
Notice that ‘ is not a valid single quote in C. Careful while copy-pasting.
1) print_xs() is a thread function and its return type should be void*. See pthread_create().
2) and 3) Not at all. The thread takes a void* as argument. Hence the function definition takes a void*. But it's not used (as its name says).
4) The & before the function is not necessary. But having it wouldn't hurt either. Both are equivalent.
1,2.) The function is returning a pointer to an unspecified data type; that means it could be any type of data, and you will be expected to already know what to do with it (any type casting, or breaking down the return into something usable - the documentation should be able to fill you in on what's coming your way).
3.) The unused parameter is a pointer to an unspecified type. Same situation, just going in the upside direction.
4.) References are a bit fuzzier for me, but if my brain isn't failing me, it's basically saying "the actual object to which thread_id is a pointer." The called function is going to be working with it as an object, instead of going through a pointer to access it.