您可能会认为您使 Consortium 结构更简单一些。由于您对每种类型、core 和 assoc 都有计数,因此您可以只有一个数组,其中第一部分用于 core,第二部分用于 assoc。
因此,您的结构将类似于以下源代码(尚未编译,只是记下而不是经过测试,因此请注意):
typedef struct {
int numCore; // number of core companies, first part of m_companies
int numAssoc; // number of assoc companies, second part of m_companies
Company m_companies[1];
} Consortium;
然后,您将通过以下方式创建您的实际数据结构:
Consortium *makeConsortium (int numCore, int numAssoc) {
Consortium *pConsortium = malloc (sizeof(Consortium) + sizeof(Company) * (numCore, numAssoc));
if (pConsortium) {
pConsortium->numCore = numCore;
pConsortium->numAssoc = numAssoc;
}
return pConsortium;
}
在此之后,您可以通过一些指示成功与否的函数来填写它:
int addCompanyCore (Consortium *pConsortium, int index, Company *pCompany) {
int iRetStatus = 0;
if (pConsortium && index < pConsortium->numCore) {
pConsortium->m_companies[index] = *pCompany;
iRetStatus = 1;
}
return iRetStatus;
}
int addCompanyAssoc (Consortium *pConsortium, int index, Company *pCompany) {
int iRetStatus = 0;
if (pConsortium && index < pConsortium->numAssoc) {
index += pConsortium->numCore;
pConsortium->m_companies[index] = *pCompany;
iRetStatus = 1;
}
return iRetStatus;
}
然后您将使用另一组辅助函数访问它们。
Company *getCompanyCore (Consortium *pConsortium, int index) {
Company *pCompany = 0;
if (pConsortium && index < pConsortium->numCore) {
pCompany = pConsortium->m_companies + index;
}
return pCompany;
}
Company * getCompanyAssoc (Consortium *pConsortium, int index) {
Company *pCompany = 0;
if (pConsortium && index < pConsortium->numAssoc) {
index += pConsortium->numCore;
pCompany = pConsortium->m_companies + index;
}
return pCompany;
}