Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

void star and & in C

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;
}
  1. 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

  2. Is it related to return value?

  3. also why void* data type is used for "unused" (void* unused)?

  4. 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.

like image 719
Fattaneh Talebi Avatar asked Jul 07 '15 05:07

Fattaneh Talebi


1 Answers

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

like image 88
GorvGoyl Avatar answered Sep 21 '22 12:09

GorvGoyl