简体   繁体   English

将结构传递给功能

[英]passing structures to functions

How do you pass structures to a function? 如何将结构传递给函数? is it the same way as with variables (ie &var1 to pass it, and *ptr_to_var from function). 它是否与变量相同(即,通过&var1传递,以及通过函数*ptr_to_var传递变量)。

Suppose in the following code I wanted to send agencies[i].emps[j].SB and agencies[i].emps[j].ANC to a function which does some calculations on them and then returns a value and store it in agencies[i].emps[j].SNET 假设在下面的代码中,我想向一个函数发送agencies[i].emps[j].SBagencies[i].emps[j].ANC ,该函数对它们进行一些计算,然后返回一个值并将其存储在agencies[i].emps[j].SNET

how do I go about that? 我该怎么办?

#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;
}

You can simple pass a structure pointer to your function: 您可以简单地将结构指针传递给函数:

// 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;    
}

Use it like this: 像这样使用它:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM