gpt4 book ai didi

c - C 中的嵌套结构

转载 作者:行者123 更新时间:2023-11-30 19:44:57 24 4
gpt4 key购买 nike

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

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com