8protons
8protons

Reputation: 3959

What does *((int *) arg) do?

I'm not familiar with the terminology to describe *((int *) arg) so I've been unable to successfully Google query the topic in order to find out more about it; I was unsuccessful in finding anything here on SO either.

Here is a snippit of code from The Linux Programming Interface:

static void *threadFunc(void *arg)
{
   int loops = *((int *) arg)
   ...
}

int main(int argc, char *argv[])
{
   pthread_t t1;
   int loops, s;

   loops = (argc > 1) ? getInt(argv[1], GN_GT_0, "num-loops") : 10000000;
   s = pthread_create(&t1, NULL, threadFunc, &loops);
   ...
}

What is int loops = *((int *) arg) doing and what is this phenomena called? Thanks.

Upvotes: 1

Views: 5497

Answers (4)

amine.ahd
amine.ahd

Reputation: 441

Judging from the arg I assume the pointer will hold a pointer to a function, this technique is used a lot in Linux and what you should probably look for is callbacks which are functions that are called with specific conditions and programmers often declare a variable that holds a generic prototype for a callback (in your case one that takes a pointer to an integer) and assign a callback to that pointer depending on the event and then call it when needed.

Upvotes: 1

t0rakka
t0rakka

Reputation: 944

It reads integer of type 'int' from the memory address in pointer variable 'arg'. The '(int *)' is a type cast so that the compiler reinterprets the bits as pointer-to-int instead of pointer-to-void.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

arg is a pointer that stores the address of a variable of type int

s = pthread_create(&t1, NULL, threadFunc, &loops);
                                          ^^^^^^

However in the function threadFunc it is declared as having type void * instead of int *

static void *threadFunc(void *arg)
                        ^^^^^^^^^

Thus in this expression

int loops = *((int *) arg)

the pointer at first interpretated again as a pointer of type int *

(int *) arg

and then it is dereferenced that to get the object it points to

*((int *) arg)

Upvotes: 2

Cubic
Cubic

Reputation: 15673

It's combining pointer dereferencing *some_pointer with casting (some_type)some_value_with_some_other_type. What this does is basically "Hey C compiler, I know you think this is a void* but I think it should be an int*, can you please treat it as such? Oh, and while you're at it, give me the int the pointer is pointing to".

Upvotes: 4

Related Questions