I'm trying to pass a function as argument to another function with void
pointer and it doesn't work
#include "header.h"
void print ( void *Arg )
{
// while ( ( int *) Arg[0] )
{
printf ( "Arg[0] = %d Arg[1] = %d\n",(int *) Arg[0], (int * ) Arg[1] );
sleep ( 1 );
//Arg[0]--;
//Arg[1]--;
}
}
void main(int argc, char **argv)
{
int count[2] = { 10, 160};
print (count);
}
I Am getting errors like this:
void*.c: In function ‘print’:
void*.c:6:52: warning: dereferencing ‘void *’ pointer [enabled by default]
printf ( "Arg[0] = %d Arg[1] = %d\n",(int *) Arg[0], (int * ) Arg[1] );
^
void*.c:6:3: error: invalid use of void expression
printf ( "Arg[0] = %d Arg[1] = %d\n",(int *) Arg[0], (int * ) Arg[1] );
^
void*.c:6:69: warning: dereferencing ‘void *’ pointer [enabled by default]
printf ( "Arg[0] = %d Arg[1] = %d\n",(int *) Arg[0], (int * ) Arg[1] );
^
void*.c:6:3: error: invalid use of void expression
printf ( "Arg[0] = %d Arg[1] = %d\n",(int *) Arg[0], (int * ) Arg[1] );
How do I fix the problem?
To print a pointer you need the
"%p"
printf
format.But it seems that you don't actually want to print the actual pointer but what it points to, and this is where your error comes from, because your casting is in the wrong place, you need to cast the pointer before you dereference it, like e.g.
It's a problem with operator precedence where the array subscript operator has higher precedence than the type-cast operator. So the compiler thinks you are doing
(int *) (Arg[0])
.