从C中的函数分配struct

use*_*960 2 c struct function

我在编写一个在C中分配结构的函数时遇到了问题.理想情况下,我希望函数使用传递给它的参数填充结构的字段.

我在头文件中定义了结构,如下所示:

typedef struct {
  char name[NAME_SIZE]; //Employee name
  int birthyear; //Employee birthyear
  int startyear; //Employee start year
} Employee;
Run Code Online (Sandbox Code Playgroud)

这就是我目前的功能:

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 */
Run Code Online (Sandbox Code Playgroud)

关于如何实现这一目标的任何建议?

dic*_*oce 6

您当前代码的问题在于,您创建的结构是在堆栈上创建的,并且一旦函数返回就会被清除.

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;
}
Run Code Online (Sandbox Code Playgroud)

这将为您提供堆分配的对象.当然,你需要一个释放内存的函数,否则就是内存泄漏.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

(顺便说一句,这种风格让你成为"面向对象"的一部分C.添加一些函数指针到结构(以获得多态行为)并且你有一些有趣的东西;虽然我在这一点上争论C++.)


kel*_*oti 5

您必须返回通过 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;
}
Run Code Online (Sandbox Code Playgroud)

还有两件事:(1)你应该使 name a 的结构定义char*而不是char[NAME_SIZE]. 分配一个 char 数组会使结构变得更大且灵活性更低。char*无论如何,您真正需要的只是一个。并且 (2) 将函数定义更改为char*.