如何将结构传递给函数?是否与变量相同(即&var1
传递它,而*ptr_to_var
来自函数。)
假设在以下代码中我想将agencies[i].emps[j].SB
和agencies[i].emps[j].ANC
发送给对它们进行一些计算的函数,然后返回一个值并将其存储在agencies[i].emps[j].SNET
我该怎么做?
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char mat[20];
double SB;
int ANC;
double RCNSS;
double SNET;
} employee;
typedef struct {
char name[20];
employee* emps;
int emps_count;
} agency;
int main(void)
{
int num_ag, num_emps, i, j;
printf("enter number of agencies\n");
scanf("%d", &num_ag);
agency* agencies = malloc(sizeof(agency) * num_ag);
for (i = 0; i < num_ag; i++) {
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) {
scanf("%s", &agencies[i].emps[j].mat);
}
}
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);
}
for (i = 0; i < num_ag; ++i) {
free(agencies[i].emps);
}
free(agencies);
return 0;
}
答案 0 :(得分:0)
您可以简单地将结构指针传递给您的函数:
// Void of a type void function, which saves result of the calculation
void modify_employee(employee * emp) {
emp->SNET = emp->SB * emp->ANC;
}
// Example of type double function, which returns result
// of of the calculation (withuot saving it)
double modify_employee2(employee * emp) {
return emp->SB * emp->ANC;
}
像这样使用:
employee* emp = malloc(sizeof(employee));
emp->SB = 20.5;
emp->ANC = 15;
printf("SNET: %f\n", emp->SNET);
modify_employee(emp);
printf("SNET: %f\n", emp->SNET);