-1

I want to pass multiple arguments to a function using a void pointer.

void* function(void *params)
{
//casting pointers
//doing something
}
int main()
{
  int a = 0
  int b = 10;
  char x = 'S';
  void function(???);
  return 0;
}

I know that I have to cast them to a certain variable in my function but I do not know how I can pass my 3 arguments as one void pointer to my function.

I have searched for this problem know quite some time but I could not find anything that would help me.

alk
  • 69,737
  • 10
  • 105
  • 255
Mark
  • 88
  • 2
  • 10

2 Answers2

2

You could do it like this:

struct my_struct
{
   int a;
   int b;
   char x;
}

void * function(void * pv)
{
  struct my_strcut * ps = pv; /* Implicitly converting the void-pointer 
                              /* passed in to a pointer to a struct. */

  /* Use ps->a, ps->b and ps->x here. */

  return ...; /* NULL or any pointer value valid outside this function */
}

Use it like this

int main(void)
{
  struct my_struct s = {42, -1, 'A'};

  void * pv = function(&s);
}

Following up on the OP's update:

struct my_struct_foo
{
   void * pv1;
   void * pv2;
}

struct my_struct_bar
{
   int a;
   int b;
}

void * function(void * pv)
{
  struct my_strcut_foo * ps_foo = pv; 
  struct my_struct_bar * ps_bar = ps_foo->pv1;

  /* Use ps_foo->..., ps_bar->... here. */

  return ...; /* NULL or any pointer value valid outside this function */
}

Use it like this

int main(void)
{
  struct my_struct_bar s_bar = {42, -1};
  struct my_struct_foo s_foo = {&s_bar, NULL};

  void * pv = function(&s_foo);
}
alk
  • 69,737
  • 10
  • 105
  • 255
  • Thank you very much alk that was exactly what I was looking for. Now I understand what I have to do. – Mark Oct 15 '18 at 08:10
1

The void* is used as a pointer to a "generic" type. Hence, you need to create a wrapping type, cast convert to void* to invoke the function, and cast convert back to your type in the function's body.

#include <stdio.h>

struct args { int a, b; char X; };
void function(void *params)
{
  struct args *arg = params;
  printf("%d\n", arg->b);
}
int main()
{
  struct args prm;
  prm.a = 0;
  prm.b = 10;
  prm.X = 'S';
  function(&prm);
  return 0;
}
Aif
  • 11,015
  • 1
  • 30
  • 44
  • 1
    Nitpicking: Your code does not cast at all. What happens is called "implicit conversion". – alk Oct 15 '18 at 08:02
  • I thought type conversion were more like integer promotion or boolean conversions.. (?) – Aif Oct 15 '18 at 08:05
  • In C there are two kinds of converting types: "Implicit Conversion" (promotion is one of this) and "Explicit Conversion", which is applied using a casting operation. Here `int i = 42; double d = ((double) i) / 7;` `i` is converted explicitly (to `double`) and `7` implicitly (to `double`) via promotion. – alk Oct 15 '18 at 08:17