c - 返回c中的结构体

标签 c arrays pointers struct return

我正在编写一个程序来定义一个结构,然后编写一个函数来创建并返回先前定义的结构。我的结构如下:

 struct Employee{
    char name[MAX_NAMES];//Symbolic constant with max set to 200
    int birthYear;
    int startYear;
    };

我的功能是[是]:

struct Employee* makeEmployee(char* nameOf, int birthYearOf, int startYearOf)
{
      struct Employee *e;
      e = (struct Employee *) malloc(sizeof(struct Employee));

      (*e).name = mystrcpy((*e).name, *nameOf);
      (*e).birthYear = birthYearOf;
      (*e).startYear = startYearOf;

      return e;
}
//edited in from comments below OP:
char* mystrcpy(char dest, const char src)
{ 
    while((*dest++ = *src++) != '\0')
    { 
        ; 
    } 
    return dest; 
}

我得到的错误是:mystring.c:在函数“makeEmployee”中: mystring.c:147:警告:传递“strcpy”的参数 2 使指针来自整数而不进行强制转换 mystring.c:147: 错误:赋值中的类型不兼容

在此处输入代码

最佳答案

要返回结构,只需通过指针返回(地址副本)即可。所以你会写:

void creat(struct employee *emp, char *name, int birthYear, int startYear)
{
    strcpy(emp->name, name);
    emp->birthYear = birthYear;
    emp->startYear = startYear;
}

在调用者中:

struct employee bob;

creat(&bob, "Bob", 1985, 2000);

现在,您可以像普通员工一样使用 bob

关于c - 返回c中的结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32662607/

相关文章:

c++ - C++中void中存储的值是什么

C++ 指向存储乱码的新内存的指针

c++ - 学习 C++ : why is this illegal?

python - 操作系统错误 : [WinError 193] %1 is not a valid Win32 application while reading custom DLL in python with CTypes

c - 如何在 32 位架构中将 64 位 unsigned long long 分配给 32 位结构

javascript - 如何提取数组的偶数元素?

javascript - PHP 到 Javascript 多维数组

c - 将指针放在哪里有关系吗? (星号)标志?

c++ - MacBook 上的 C 和 C++ 编程

c++ - C++14 中的可变长度数组?