使用空指针传递多个值的参数

时间:2018-10-15 07:47:43

标签: c struct parameter-passing void-pointers

我想使用空指针将多个参数传递给函数。

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

我知道我必须将它们强制转换为函数中的某个变量,但是我不知道如何将3个参数作为一个空指针传递给函数。

我搜索这个问题已经有一段时间了,但是找不到任何可以帮助我的东西。

2 个答案:

答案 0 :(得分:2)

您可以这样做:

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 */
}

像这样使用它

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

  void * pv = function(&s);
}

紧跟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 */
}

像这样使用它

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);
}

答案 1 :(得分:1)

void *用作指向“通用”类型的指针。因此,您需要创建一个包装类型,将 cast 转换为void *以调用该函数,然后将 cast 转换回函数主体中的类型。

#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;
}
相关问题