下面是您可能考慮的一個示例。這是你必須要做的模板,你只需操縱員工,代理機構名稱等等。 (請注意,沒有錯誤檢查,這是不好的。)
#include <stdio.h>
#include <stdlib.h>
/* TODO: modify members */
typedef struct {
int id;
int salary;
} employee;
/* TODO: modify members */
typedef struct {
char name[20];
employee* emps;
int emps_count;
} agency;
/* return sum of id and salary for first employee from agency */
int dumb_calc(agency ag) {
return ag.emps[0].id + ag.emps[0].salary;
}
int main(void)
{
int num_ag;
int num_emps;
int i, j;
printf("enter num of agencies:\n");
scanf("%d", &num_ag);
agency* agencies = malloc(sizeof(agency) * num_ag);
for (i = 0; i < num_ag; ++i) {
/* TODO: modify single agency name */
sprintf(agencies[i].name, "agency %d", i+1);
printf("enter num of employees for agency %d\n", i+1);
scanf("%d", &num_emps);
agencies[i].emps = malloc(sizeof(employee) * num_emps);
agencies[i].emps_count = num_emps;
for (j = 0; j < num_emps; ++j) {
/* TODO: modify single employee */
agencies[i].emps[j].id = j+1;
agencies[i].emps[j].salary = 1000*(j+1);
}
}
/* TODO: change printing style */
for (i = 0; i < num_ag; ++i) {
printf("agency name: %s\n", agencies[i].name);
printf("num of employees: %d\n", agencies[i].emps_count);
/* result will always be the same */
printf("sum of id and salary for 1st emp: %d\n", dumb_calc(agencies[i]));
}
/* remember to free what you've alloc'd */
for (i = 0; i < num_ag; ++i) {
free(agencies[i].emps);
}
free(agencies);
return 0;
}
您以前使用過'malloc'嗎? – doctorlove 2014-11-24 12:21:43
爲您的結構分配內存並存儲輸入的值 – Gopi 2014-11-24 12:22:04