2011-02-06 52 views
1

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

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

typedef struct { 
    char name[NAME_SIZE]; //Employee name 
    int birthyear; //Employee birthyear 
    int startyear; //Employee start year 
} Employee; 

而这就是我对目前我的功能:

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 */ 

如何做到这一点有什么建议?

+2

我认为这将是有益的,如果你能介绍更多你想如何此功能将使用什么与创建的结构做了一点。你如何在C中分配内存和创建数据结构很大程度上取决于你如何计划使用它们。 – linuxuser27 2011-02-06 03:18:03

回答

1

你必须返回通过的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; 
} 

两件事:(1)你应该做的名字的char*代替char[NAME_SIZE]的结构定义。分配一个char数组会使结构变得更大,更不灵活。无论如何,你真正需要的是一个char*。 (2)将功能定义更改为char*

+0

我不知道你给点(1)的建议......只要`NAME_SIZE`是一个合理的大小,它真的不值得它做对 - 动态分配内存并且必须管理它。没有必要使其复杂化。 – 2011-02-06 03:36:46

5

您当前的代码存在的问题是您创建的结构在堆栈上创建,并且只要函数返回就会被清除。

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; 
} 

这会给你一个堆分配对象。当然,你需要一个释放内存的函数,或者这是一个内存泄漏。

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); 
    } 
} 

(顺便说一句,这种风格让你的方式向部分C.添加一些函数指针的struct的“面向对象”(获得多态行为),你有一些有趣的事情,但我要说对C++在这一点上)

1
Employee * make_employee(char *_name, int birth_year, int start_year) 
{ 
    Employee *employee; 

    if (employee = (struct Employee *)memalloc(sizeof(Employee)) == NULL) 
    { 
     return NULL; 
    } 
    else 
    { 
     strcpy(&(employee->name), _name); 
     employee->birthyear = birth_year; 
     employee->startyear = start_year; 
     return employee; 
    } 
} 
1
  1. 为什么会出现使员工返回空隙?您需要从make_employee函数返回Employee!

  2. 您是否遇到编译器抱怨x = {a,...}语法的问题?写得很长,然后:Emp e; e.field1 = a; ...

  3. 你有奇怪的覆盖/伪造数字问题?如果你在函数中分配一个结构体,一旦函数返回,它就会变得无效(并且容易被覆盖)!去解决这一点,你要么必须:

    • 返回该结构的副本(这是确定的小结构):

      Employee make_emp(int a){ 
          Emp emp; //Allocate temporary struct 
          emp.filed1 = a; //Initialize fields; 
          return emp; // Return a copy 
      } 
      
    • 分配结构堆中,而不是处理就行了通过引用(即:指针),而不是:

      Employee* make_emp(int a){ 
          Emp* emp = malloc(sizeof(Emp)); //Allocate the struct on the heap 
                  //And get a reference to it 
          emp->filed1 = a; //Initialize it 
          return emp; //Return the reference 
      } 
      

      你在这种情况下,用它做后,不要忘了free()员工!