Structure with Function in C

The C language supports the passing of structure values as arguments to function. When a structure is used as an argument to a function, the entire structure is passed using the standard call-by-value method. It means that any changes made to the contents of the structure inside the function to which it is passed do not affect the structure used as an argument.

The general format of sending a copy of a structure to the called function is :
 function_name( struture_variable_name);
And at the function declaration, we also need to define the structure type in parameters, the format is :
data_type function_name(struct structure_name structure_variable) {
  .................
  // function statements 
  .................
}
Now lets see a C example code :
#include <stdio.h>
#include <string.h>

struct details {
  char name[30];
  int age;
  char occupation[20];
  char address[30];
  char phoneNo[20];
};

void printDetails(struct details obj) {
  printf("Name : %s\n", obj.name);
  printf("Age : %d\n", obj.age);
  printf("Occupation : %s\n", obj.occupation);
  printf("Address : %s\n", obj.address);
  printf("Phone No. : %s\n", obj.phoneNo);
}

int main() {

  struct details dt1;

  strncpy(dt1.name, "Shyam Kumar", 30);
  dt1.age = 25;
  strncpy(dt1.occupation, "Web-Developer", 20);
  strncpy(dt1.address, "Raipur, India", 30);
  strncpy(dt1.phoneNo, "9876543210", 20);

  printDetails(dt1);
  return 0;
}
Output :

Name : Shyam Kumar
Age : 25
Occupation : Web-Developer
Address : Raipur, India
Phone No. : 9876543210

Passing structure members to Functions :

We can also pass a structure member to a function. Example :
#include <stdio.h>
#include <string.h>

struct details {  
  char name[30];
  int age;
  char occupation[20];
  char address[30];
  char phoneNo[20];
};

void printD1(int x) {
  printf("%d\n", x);
}

void printD2(char str[]) {
  printf("%s\n", str);
}

int main() {

  struct details dt1;

  strncpy(dt1.name, "Shyam Kumar", 30);
  dt1.age = 25;
  strncpy(dt1.occupation, "Web-Developer", 20);
  strncpy(dt1.address, "Raipur, India", 30);
  strncpy(dt1.phoneNo, "9876543210", 20);

  printf("Name : ");
  printD2(dt1.name);
  printf("Age : ");
  printD1(dt1.age);
  printf("Occupation : ");
  printD2(dt1.occupation);
  printf("Address : ");
  printD2(dt1.address);
  printf("Phone No. : ");
  printD2(dt1.phoneNo);
  return 0;
}
Output :

Name : Shyam Kumar
Age : 25
Occupation : Web-Developer
Address : Raipur, India
Phone No. : 9876543210

Next Topic :