-2
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

In this situation, I want to make functions that use typedef variables as arguments.

For example, if I make a function like void print_line() that print age, height, weight , what should I write in ()? At first I wrote void print_line(Person); But VS says it's an error.

Please help me.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
ssrr00
  • 13
  • 3

1 Answers1

2

How to use typedef variables to functions as arguments

Just like you use the build-in types.

That's the whole idea behind typedef - you create your own type and use it like any other type.

If you want to pass an int you do

void foo(int input) {...}

If you want to pass you own type you do

typedef ...... myType;

void foo(myType input) {...}

Off topic:

Your code:

Person *p=(Person*)malloc(sizeof(int)*20);

is wrong! Don't use sizeof(int) as your type Person doesn't have that size. Less important - but still - in C you don't cast malloc. The way to do it is:

    Person *p=malloc(20 * sizeof *p);  // Allocate memory for 20 Person

or

    Person *p=malloc(20 * sizeof(Person));   // Allocate memory for 20 Person

But the first is to be preferred.

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63