Void star and & in C

I'm having trouble with a pointer in C, this is an example of a stream in C. this code was written in the book Advanced Linux Programming:

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 there void*

    ?

    I found the answer, but it wasn't clear enough for me. answer: This declares a pointer, but without specifying what datatype it points to

  • Is it related to the return value?

  • also why is the void * datatype used for "void * unused"?

  • I'm not sure 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 him to execute the pthread_create function, but he does not know where this function is, so we point to it the address of this function.

+3


source to share


3 answers


A void (void *) pointer is a pointer that has no data type associated with it. A void pointer can contain an address of any type and can be typed 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, it void* print_xs()

has a void pointer return type.

pthread_create (&thread_id, NULL, &print_xs, NULL);

pthread_create

passes the address to the function thread_id

andprint_xs

+6


source


Note that

this is not a valid single quote in C. Careful while you copy.

1) print_xs()

is a stream function and its return type must be void*

. See pthread_create () .



2) and 3) Not at all. The stream takes an argument void*

. Hence the function definition takes a void*

. But it is not used (as its name says).

4) &

before the function is not required. But it doesn't hurt either. Both are equivalent.

+3


source


1,2.) The function returns a pointer to an unspecified data type; this means it can be any datatype, and you are expected to already know what to do with it (casting of any type, or breaking back to something useful), the documentation should be able to fill you with what comes on your way).

3.) An unused parameter is a pointer to an unspecified type. The same situation, only in the upward direction.

4.) The links are a bit crazier for me, but if my brain doesn't let me down, it basically says "the actual object to which the thread_id is a pointer". The called function will work with it as an object, and not through a pointer to access it.

+2


source







All Articles