问题描述
typedef struct {
int age,height,weight;
} Person;
//this is in global variables
...
Person *p = (Person *)malloc(sizeof(int) * 20); //this is local variable in main function
在这种情况下,我想制作使用typedef变量作为参数的函数。
例如,
如果我使用void print_line()
之类的功能来打印年龄,身高,体重,该如何写()
?
起初我写了void print_line(Person);
,但VS表示这是一个错误。
请帮助我。
解决方法
如何使用typedef变量作为参数
就像您使用内置类型一样。
这就是typedef
背后的全部思想-您创建自己的类型并将其像其他类型一样使用。
如果您想通过int
,则可以这样做
void foo(int input) {...}
如果您想通过自己的类型,请输入
typedef ...... myType;
void foo(myType input) {...}
主题外:
您的代码:
Person *p=(Person*)malloc(sizeof(int)*20);
错了!请勿使用sizeof(int)
,因为您的类型Person
的大小没有限制。不那么重要-仍然-在C语言中,您不会强制转换malloc
。这样做的方法是:
Person *p=malloc(20 * sizeof *p); // Allocate memory for 20 Person
或
Person *p=malloc(20 * sizeof(Person)); // Allocate memory for 20 Person
但是第一个是首选。