简体   繁体   English

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

[英]how to give a struct * as argument to a function

I want to pass alloc as an argument but don't know how, can somebody help me? 我想将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);
}

in parameter I want to free(alloc) 在参数中我想释放(分配)

I have hoped that it would function this way: 我希望它可以这样运行:

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

but then I get this 但后来我明白了

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'

You are getting warning incompatible pointer type because you are using struct resistor before declaration: 您将得到警告incompatible pointer type因为在声明之前使用了struct resistor

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

In your program, the declaration of struct resistor is after parameter() function. 在您的程序中, struct resistor的声明在parameter()函数之后。
You can solve this problem by either moving the struct resistor declaration before function parameter() or just do the forward declaration of struct resistor before parameter() function, like this: 您可以通过将struct resistor声明移到函数parameter()之前,或者只是在parameter()函数之前进行struct resistor的正向声明来解决此问题,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM