I'm new and i try to create a struct of stuct on C code. I don't understand how i can inizialize a struct of struct. Someneone help me? I have:
#define SIZEHOSP 200
#define DIM 200
#define SIZESICK 2000
typedef struct SICKREGION {
char firstName[20];
char lastName[20];
char fiscalCode[16];
enum stateSick;
diagnosisDate data;
healingDate dataH;
};
typedef struct HOSPITAL {
char nameHospital[30];
int codeHospital;
char addressHospital[40];
char departmentManager[30];
int beds;
int bedsIntensiveCare;
};
HOSPITAL hospital[SIZEHOSP];
typedef struct REGION {
char nameRegion[20];
int codeRegion;
char MainTownRegion[15];
char namePresidentRegion[20];
int numberHospital;
int numberSickRegion;
HOSPITAL hospital[SIZEHOSP];
SICKREGION sickregion[SIZESICK];
};
REGION region[DIM] = {
{"Sicilia", 0004, "Palermo", "Musumeci", 40, 150},
{"sardegna", 4444, "cagliari", "pippo", 200, 50},
{"calabria", 0000, "reggio", "Josh", 12, 18}
};
for example i inizialized 3 type of REGION. but they are incomplete because i don't know how insert the value of structure HOSPITAL and SICKREGION inside the region[DIM]. What is the syntax? I hope he explained the problem well.
How do I initialize a struct containing another struct?
There are several ways to initialize a struct. To simplify, the following example uses smaller structs than those you provided...
The following will illustrate initialization with initialization with values ( = {,,,{,,}};
), then with zeros = {0}
:
typedef struct {
int count;
float cash;
char item[50];
}Purchase;
typedef struct {
int accnt;
char acct_name[50];
Purchase purch;
} Acct;
Acct acct = {100123, "Robert Baily", {15, 12.50, "Tires"}};
//Or, using member names to self document the initialization statement as suggested in comments:
Acct acct1 = Acct acct = {.accnt=100123, .acct_name="Robert Baily", {.count=15, .cash=12.50, .item="Tires"}};
Acct acct2 = {0};
int main(void)
{
printf("acct = %d\nAcct_name = %s\nitem = %s\ncount = %d\ncash = %3.2f\n", acct.accnt, acct.acct_name, acct.purch.item, acct.purch.count, acct.purch.cash);
printf("acct2 = %d\nAcct_name = %s\nitem = %s\ncount = %d\ncash = %3.2f\n", acct2.accnt, acct2.acct_name, acct2.purch.item, acct2.purch.count, acct2.purch.cash);
return 0;
}
Although these are small, they illustrate what you are doing with your larger, more complicated structs. I suggest that for your structs it will be extremely tedious, and probably not necessary to use the first method. struct
declaration in an actual program is often initialized by zeroing. i.e. {0}