I’m having issues writing a function that allocates a struct in C. Ideally, I want to have the function fill the fields of the struct with parameters passed into it.
I have defined the struct in my header file like so:
typedef struct {
char name[NAME_SIZE]; //Employee name
int birthyear; //Employee birthyear
int startyear; //Employee start year
} Employee;
And this is what I have for my function currently:
void make_employee(char _name, int birth_year, int start_year) {
Employee _name = {_name,birth_year,start_year}; //allocates struct with name
} /* end make_employee function */
Any advice on how to accomplish this?
You have to return a pointer allocated via malloc:
two more things: (1) you should make the struct definition of name a
char*instead ofchar[NAME_SIZE]. Allocating a char array makes the struct much bigger and less flexible. All you really need is achar*anyway. And (2) change the function definition tochar*.