Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

C Structure & Functions

Passing structure member to function

Example

#include <stdio.h>

struct Employee
{
    int id_no;
    char name[30];
    float salary;
};
void show(int id, char emp_name[], float sal);
                         
int main()
{
    struct Employee emp = {10,"Tom",45000.50};
    show(emp.id_no,emp.name,emp.salary);
    return 0;
}

void show(int id, char emp_name[], float sal)
{
    printf("\n id_no of emp = %d",id);
    printf("\n name of emp = %s",emp_name);
    printf("\n salary of emp = %f",sal);
}

Output

id_no of emp = 10
name of emp = Tom
salary of emp = 45000.500000

Passing structure to function

There are two ways to pass structure variable.

i) Call by value
ii) Call by reference

Call by value

Example

#include <stdio.h>

struct Employee
{
    int id_no;
    char name[30];
    float salary;
};
void show(struct Employee emp);

int main()
{
    struct Employee emply = {10,"Robin",55500.63};
    show(emply);
    return 0;
}

void show(struct Employee emp)
{
    printf("\n id_no = %d",emp.id_no);
    printf("\n name = %s",emp.name);
    printf("\n salary = %f",emp.salary);
}

Output

id_no = 10
name = Robin
salary = 55500.628906

Call by reference

Example

#include <stdio.h>

struct Employee
{
    int id_no;
    char name[30];
    float salary;
};

void show(struct Employee *ptr);

int main()
{
    struct Employee emp = {100,"Ricky",23453.00};
    show(&emp);
    return 0;
}

void show(struct Employee *ptr)
{
    printf("\n id_no = %d",ptr->id_no);
    printf("\n name = %s",ptr->name);
    printf("\n salary = %f",ptr->salary);
}

Output

id_no = 100
name = Ricky
salary = 23453.000000

 

Leave a reply