Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocate struct from function in C

Tags:

c

function

struct

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?

like image 655
user604960 Avatar asked Dec 04 '22 09:12

user604960


2 Answers

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.

struct foo
{
    int a;
    int b;
};

struct foo* create_foo( int a, int b )
{
    struct foo* newFoo = (struct foo*)malloc( sizeof( struct foo ) );
    if( newFoo )
    {
        newFoo->a = a;
        newFoo->b = b;
    }
    return newFoo;
}

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.

void destroy_foo( struct foo* obj )
{
    if( obj )
        free( obj );
}

void print_foo( struct foo* obj )
{
    if( obj )
    {
        printf("foo->a = %d\n",obj->a);
        printf("foo->b = %d\n",obj->b);
    }
}

(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.)

like image 183
dicroce Avatar answered Dec 22 '22 15:12

dicroce


You have to return a pointer allocated via malloc:

Employee* new_employee(char *_name, int birth_year, int start_year) {
    struct Employee* ret = (struct Employee*)malloc(sizeof(struct Employee));
    ret->name = _name;
    ret->birth_year = birth_year;
    ret->start_year = start_year;
    return ret;
}

two more things: (1) you should make the struct definition of name a char* instead of char[NAME_SIZE]. Allocating a char array makes the struct much bigger and less flexible. All you really need is a char* anyway. And (2) change the function definition to char*.

like image 34
kelloti Avatar answered Dec 22 '22 14:12

kelloti