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?
Why does the make Employee return void? You need to return the Employee from the make_employee function!
Are you having trouble with the compiler complaining about the
x = {a,...}
syntax? Write it the long way then:Emp e; e.field1 = a; ...
Are you having weird overwriting / bogus numbers problems? If you allocate a struct in the function it will become invalid (and prone to being overwriten) as soon as the function returns! To go around this you either have to:
Return a copy of the struct (this is OK for small structs):
Allocate the struct in the heap instead and deal with it through references (ie.: pointers) instead:
Don't forget to
free()
the Employee after you are done with it in this case!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*
.The problem with your current code is that the struct your creating is created on the stack and will be cleaned up as soon as the function returns.
This will get you a heap allocated object. Of course, you'll need a function to free that memory or this is a memory leak.
(btw, this style gets you part of the way toward an "object oriented" C. Add some function pointers to the struct (to get polymorphic behavior) and you have something interesting; though I'd argue for C++ at that point.)