c - C 中的嵌套结构

标签 c structure

目标:询问用户机构的数量,创建所述机构,并为每个机构询问员工数量,并创建这些员工。

我认为,其中一部分需要嵌套结构,例如

typedef struct agence agence;
struct agence
{
    char nom[20];
    int nmbrEmp;
    struct employe
    {
        char mat[20];
        int nmbrEnf;
        int ANC;
        double SB;
        double RCNSS;
    }
};

这是正确的路径吗?一旦用户向您提供了每个机构/员工所需的数量,您如何继续创建机构/员工的数量。

最佳答案

与 C++ 不同,C 不能有嵌套类型,您必须单独声明它们。

struct employe
{
    char mat[20];
    int nmbrEnf;
    int ANC;
    double SB;
    double RCNSS;
};

struct agence
{
    char nom[20];
    int nmbrEmp;
    struct employe * employees; // pointer to an array of employees
};

然后使用动态内存并填充它们:

struct agence * agencies;
size_t num_agencies = 100;

agencies = calloc(sizeof(*agencies), num_agencies);

for (/* read egancies somehow */) {
    agencies[i].nmbrEmp = number_employees;
    agencies[i].employees = calloc(sizeof(agencies[i].employees[0]), number_employees);

    // write agencies[i].employees[j] ...
}

关于c - C 中的嵌套结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27104731/

相关文章:

c - 这是未定义的行为还是正常输出

c - K&R练习2.6位操作

c - 从 C 中的 FIFO 链接列表中弹出函数不起作用

C++ - 如何写入和读取包含对象的结构? (写入和读取二进制文件)

c - fopen\fopen_s 在 c 中通过命令行编译和运行时

c - 我的 UDP 客户端服务器出了什么问题?

php - Facebook-wall like MySQL结构问题

java - 我如何读取java项目的文件结构?

c - C程序运行时出现错误

C 编程 - 灵活数组成员的非静态初始化