从C函数分配结构

从C函数分配结构

本文介绍了从C函数分配结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

这就是我目前的功能:

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?

推荐答案

您必须返回通过malloc分配的指针:

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

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

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

这篇关于从C函数分配结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:59