如何将struct *作为函数的参数

时间:2019-01-05 10:29:42

标签: c

我想将alloc作为参数传递,但是不知道如何,有人可以帮助我吗?

void parameter(unsigned int argnum, struct resistor* alloc)
{
/*...*/
}

struct resistort
{
  const double E6[6];
  double E12[12];
  const double E24[24];
  char e[3];
  double value;
  double log10val;
  double val;
  double serielval[2];
  double reset;
}rv;

int main(int argc, char *argv[])
{
  struct resistor *alloc = NULL;
  alloc = (struct resistor *)malloc(sizeof(struct resistor));

  parameter(argc, alloc);
}

在我想要释放(分配)的参数中

我希望它可以这样运行:

void parameter(unsigned int argnum, struct resistor* alloc);

但是我明白了

warning: passing argument 2 of 'parameter' from incompatible pointer type [-Wincompatible-pointer-types]|
note: expected 'struct resistor *' but argument is of type 'struct resistor *'
error: conflicting types for 'parameter'

1 个答案:

答案 0 :(得分:4)

您收到警告incompatible pointer type,因为您在声明前使用了struct resistor

void parameter(unsigned int argnum, struct resistor* alloc)
                                    ^^^^^^^^^^^^^^^

在您的程序中,struct resistor的声明在parameter()函数之后。
您可以通过将struct resistor声明移至函数parameter()之前来解决此问题,或者只需在struct resistor函数之前进行parameter()的前向声明,如下所示:

struct resistor; //forward declaration 

void parameter(unsigned int argnum, struct resistor* alloc)
{
/*...*/
}

struct resistor
{
    const double E6[6];
    double E12[12];
    const double E24[24];
    char e[3];
    double value;
    double log10val;
    double val;
    double serielval[2];
    double reset;
}rv;

int main(int argc, char *argv[])
{
    struct resistor *alloc = NULL;
    alloc = (struct resistor *)malloc(sizeof(struct resistor));

    parameter(argc, alloc);
}