randsimo
randsimo

Reputation: 9

passing structures to functions

How do you pass structures to a function? is it the same way as with variables (i.e. &var1 to pass it, and *ptr_to_var from function).

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

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

Upvotes: 0

Views: 90

Answers (1)

syntagma
syntagma

Reputation: 24354

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

Upvotes: 0

Related Questions