 Structures in Functions
 Pointers to structures
 Accessing structure members
 Using pointer as a function argument
 Array of structures
 Array of structures
 Self referential structures.
 Like all other types, we can pass structures as
arguments to a function.
 In fact, we can pass, individual members, structure
variables, a pointer to structures etc to the function.
 Similarly, functions can return either an individual
 Similarly, functions can return either an individual
member or structures variable or pointer to the
structure.
 Passing Structure Members as arguments to Function
 Passing Structure Variable as Argument to a Function
 Returning Structure from Function
#include<stdio.h>
/*
structure is defined above all functions so it is global.
*/
struct student
struct student
{
char name[20];
int roll_no;
int marks;
};
void print_struct(char name[], int roll_no, int marks);
Output
Name: Tim
Roll no: 1
Marks: 78
int main()
{
struct student stu = {"Tim", 1, 78};
print_struct(stu.name, stu.roll_no,stu.marks);
return 0;
} Marks: 78
}
void print_struct(char name[], int roll_no, int marks)
{
printf("Name: %sn", name);
printf("Roll no: %dn", roll_no);
printf("Marks: %dn", marks);
printf("n");
}
 If a structure contains two-three members then we
can easily pass them to function but what if there
are 9-10 or more members ?
 Certainly passing 9-10 members is a tiresome and
error-prone process. So in such cases instead of
passing members individually, we can pass
structure variable itself.
#include<stdio.h>
/*structure is defined above all functions so it is global. */
struct student
{
char name[20];
char name[20];
int roll_no;
int marks;
};
void print_struct(struct student stu);
OUTPUT
Name: George
Roll no: 10
Marks: 69
int main()
{
struct student stu = {"George", 10, 69};
print_struct(stu);
return 0;
Marks: 69
return 0;
}
void print_struct(struct student stu){
printf("Name: %sn", stu.name);
printf("Roll no: %dn", stu.roll_no);
printf("Marks: %dn", stu.marks);
printf("n");
}
 Although passing structure variable as an argument allows us to pass
all the members of the structure to a function there are some
downsides to this operation.
 Recall that a copy of the structure is passed to the formal argument.
 Recall that a copy of the structure is passed to the formal argument.
If the structure is large and you are passing structure variables
frequently then it can take quite a bit of time which make the
program inefficient.
 Additional memory is required to save every copy of the structure.
#include<stdio.h>
/*structure is defined above all functions so it is global.
*/
struct employee
{
{
char name[20];
int age;
char doj[10]; // date of joining
char designation[20];
};
void print_struct(struct employee *);
int main()
{
struct employee dev = {"Jane", 25, "25/2/2015", "Developer"};
print_struct(&dev);
return 0;
}
}
void print_struct(struct employee *ptr)
{
printf("Name: %sn", ptr->name);
printf("Age: %dn", ptr->age);
printf("Date of joining: %sn", ptr->doj);
printf("Age: %sn", ptr->designation);
printf("n");
}
 To return a structure from a function we must
specify the appropriate return type in the function
definition and declaration.
struct player check_health(struct player p);
{
{
...
}
 This function accepts an argument of type struct
player and returns an argument of type struct
player.
#include<stdio.h>
/*structure is defined above all functions so it is global.
*/
struct player
{
void print_struct(struct player p);
struct player deduct_fees(struct player p);
int main()
{
char name[20];
float height;
float weight;
float fees;
};
int main()
{
struct player p = {"Joe", 5.9, 59, 5000 };
print_struct(p);
p = deduct_fees(p);
print_struct(p);
return 0;
}
struct player deduct_fees(struct player p)
{
p.fees -= 1000;
return p;
}
OUTPUT
Name: Joe
Height: 5.90
Weight: 59.00
}
void print_struct(const struct player p)
{
printf("Name: %sn", p.name);
printf("Height: %.2fn", p.height);
printf("Weight: %.2fn", p.weight);
printf("Fees: %.2fn", p.fees);
printf("n");
}
Weight: 59.00
Fees: 5000.00
Name: Joe
Height: 5.90
Weight: 59.00
Fees: 4000.00
 Structures in Functions
 Pointers to structures
 Accessing structure members
 Using pointer as a function argument
Array of structures
 Array of structures
 Self referential structures.
 A pointer to a structure must be defined
before it is pointed to a structure variable
struct student {
char name[50];
char name[50];
int age;
}s1={"Sanju",12};
struct student *p;
p = &s1; //p points to
 Structures in Functions
 Pointers to structures
 Accessing structure members
 Using pointer as a function argument
 Array of structures
 Array of structures
 Self referential structures.
 The structure members can be accessed in three
ways; two of them use a pointer with standard and
special notation.
 rect1.length //The standard access mechanism that doesn’t use
a pointer.
a pointer.
 (*p).length //Pointer dereferenced with * and then connected to
the member.
 p->length //Uses a special operator, ->, that works only with
structures.
 The structure members can be accessed in three ways;
two of them use a pointer with standard and special
notation.
//The standard access mechanism that doesn’t use a pointer.
printf("Name: %sn", s1.name);
printf("Age: %dn", s1.age);
printf("Age: %dn", s1.age);
//Pointer dereferenced with * and then connected to the member.
printf("Name: %sn",(*p).name);
printf("Age: %dn", (*p).age);
//Uses a special operator, ->, that works only with structures.
printf("Name: %sn",p->name);
printf("Age: %dn", p->age);
#include <stdio.h>
#include <string.h>
int main(void)
{
struct employee
{
short id;
char name[30];
int pay;
int pay;
} emp = {1024, “Steve Wozniak”, 10000}, *p;
p = &emp;
printf(“Emp-id: %hd, Name: %s, Pay: %dn”, emp.id, (*p).name, p->pay);
(*p).id = 4201; /* Updates id */
strcpy(p->name, “Steve Jobs”); /* Updates name */
p->pay = 20000; /* Updates pay */
printf(“Emp-id: %hd, Name: %s, Pay: %dn”, p->id, p->name, p->pay);
return 0;
}
Output:
Emp-id: 1024, Name: Steve Wozniak, Pay: 10000
Emp-id: 4201, Name: Steve Jobs, Pay: 20000
 Structures in Functions
 Pointers to structures
 Accessing structure members
 Using pointer as a function argument
 Array of structures
 Array of structures
 Self referential structures.
 A structure variable can be passed as function arguments
 This will behave as pass-by-value.
 This mechanism is safe and it protects the original structure
from modification by the function.
from modification by the function.
 However, large structures can consume a lot of memory, so we
may need to pass a pointer to a structure instead of the entire
structure.
 Updating a member’s value using a pointer represents a
memory-efficient technique because the function copies not the
structure (36 bytes) but its pointer (4 bytes).
/* update_pay.c: Uses a pointer to a structure as a function argument to update the structure. */
#include <stdio.h>
struct employee
{
short id;
char name[30];
int pay;
} emp = {1024, “Steve Wozniak”, 10000};
void update_pay(struct employee *f_emp, int f_pay);
int main(void)
{
printf(“Old pay = %dn”, emp.pay);
update_pay(&emp, 20000);
printf(“New pay = %dn”, emp.pay);
return 0;
}
void update_pay(struct employee *f_emp, int f_pay)
{
f_emp->pay = f_pay; /* Updates member pay of emp */
}
OUTPUT:
Old pay = 10000
New pay = 20000
 Structures in Functions
 Pointers to structures
 Accessing structure members
 Using pointer as a function argument
 Array of structures
 Array of structures
 Self referential structures.
 We used two structure variables, stud1 and stud2, to handle
data of two students.
 This technique won’t work with 500 students.
 C supports an array of structures, whose definition may or may
not be combined with the declaration of the structure.
 The following statement defines an array of type struct student
that can hold 50 sets (or records) of student data.
that can hold 50 sets (or records) of student data.
 Alternatively, you can separate the declaration and definition.
 You can also use typedef to replace struct student with
STUDENT.
 Because stud is an array, its elements are laid out contiguously
in memory.
 The size of each array element is equal to the size of the
structure in memory after accounting for slack bytes.
 Pointer arithmetic can easily be employed here to access each
array element, and using a special notation (->)
 This array can be partially or fully initialized by enclosing the
initializers for each array element in a set of curly braces.
 Each set is separated from its adjacent one by a comma, while
the entire set of initializers are enclosed by outermost braces:
 Each member of each element of this array is accessed by using
a dot to connect the member to its array element.
 You can use scanf to input values to each member using
pointers to these variables (like &stud[i].marks).
 A simple for loop using the array index as the key variable
prints the entire list
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
};
int main()
{
int i;
struct student record[2];
// 1st student's record
record[0].id=1;
strcpy(record[0].name, "Raju");
record[0].percentage = 86.5;
// 2nd student's record
record[1].id=2;
strcpy(record[1].name, "Surendren");
record[1].percentage = 90.5;
// 3rd student's record
record[2].id=3;
strcpy(record[2].name, "Thiyagu");
record[2].percentage = 81.5;
record[2].percentage = 81.5;
for(i=0; i<3; i++)
{
printf(" Records of STUDENT : %d n", i+1);
printf(" Id is: %d n", record[i].id);
printf(" Name is: %s n", record[i].name);
printf(" Percentage is: %fnn",record[i].percentage);
} return 0;
}
OUTPUT:
Records of STUDENT : 1
Id is: 1
Name is: Raju
Percentage is: 86.500000
Records of STUDENT : 2
Id is: 2
Id is: 2
Name is: Surendren
Percentage is: 90.500000
Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.500000
 Structures in Functions
 Pointers to structures
 Accessing structure members
 Using pointer as a function argument
 Array of structures
 Array of structures
 Self referential structures
 A structure can have members which point to a structure variable of the same type.
 These types of structures are called self referential structures and are widely used in
dynamic data structures like trees, linked list, etc.
 Syntax to define self referential structure
struct node
{
---
---
---
struct node *next;
};
Here, next is a pointer to a struct node variable.
 It should be remembered that a pointer to a structure is similar to a pointer to any
other variable
 A self referential data structure is essentially a structure definition which includes at
least one member that is a pointer to the structure of its own kind.
struct student
{
char name[20];
int roll;
char gender;
int marks[5];
struct student *next;
};
 This is a self-referential structure where next is a struct student type
structure pointer.
 We will now create two structure variables stu1 and stu2 and initialize
them with values.
 We will then store the address of stu2 in next member of stu1.
void main()
{
struct student stu1 = {"Alex", 43, 'M', {76, 98, 68, 87, 93}, NULL};
struct student stu2 = { "Max", 33, 'M', {87, 84, 82, 96, 78}, NULL};
stu1.next = &stu2;
}
}
 We can now access the members of stu2 using stu1 and next
void main()
{
printf("Name: %sn", stu1.next->name);
printf("Roll: %dn", stu1.next->roll);
printf("Roll: %dn", stu1.next->roll);
printf("Gender: %cn", stu1.next->gender);
for(int i = 0; i < 5; i++)
printf("Marks in %dth subject: %dn",i,stu1.next->marks[i]);
}
 OUTPUT
Name: Max
Roll: 33
Gender: M
Gender: M
Marks in 0th subject: 87
Marks in 1th subject: 84
Marks in 2th subject: 82
Marks in 3th subject: 96
Marks in 4th subject: 78
 Suppose we want a different structure variable after stu1,
that is insert another structure variable between stu1 and
stu2. This can be done easily.
void main()
{
struct student stu3 = { "Gasly", 23, 'M', {83, 64, 88, 79, 91},
NULL};
NULL};
st1.next = &stu3;
stu3.next = &stu2;
}
 Now stu1.next stores the address of stu3. And stu3.next has
the address of stu2. We can now access all three structures
using stu1.
printf("Roll Of %s: %dn", stu1.next->name, stu1.next->roll);
printf("Gender Of %s: %cn", stu1.next->next->name,
stu1.next->next->gender);
stu1.next->next->gender);
 OUTPUT
Roll Of Gasly: 23
Gender Of Max: M
Pointers and Structures

Pointers and Structures

  • 2.
     Structures inFunctions  Pointers to structures  Accessing structure members  Using pointer as a function argument  Array of structures  Array of structures  Self referential structures.
  • 3.
     Like allother types, we can pass structures as arguments to a function.  In fact, we can pass, individual members, structure variables, a pointer to structures etc to the function.  Similarly, functions can return either an individual  Similarly, functions can return either an individual member or structures variable or pointer to the structure.  Passing Structure Members as arguments to Function  Passing Structure Variable as Argument to a Function  Returning Structure from Function
  • 4.
    #include<stdio.h> /* structure is definedabove all functions so it is global. */ struct student struct student { char name[20]; int roll_no; int marks; }; void print_struct(char name[], int roll_no, int marks);
  • 5.
    Output Name: Tim Roll no:1 Marks: 78 int main() { struct student stu = {"Tim", 1, 78}; print_struct(stu.name, stu.roll_no,stu.marks); return 0; } Marks: 78 } void print_struct(char name[], int roll_no, int marks) { printf("Name: %sn", name); printf("Roll no: %dn", roll_no); printf("Marks: %dn", marks); printf("n"); }
  • 6.
     If astructure contains two-three members then we can easily pass them to function but what if there are 9-10 or more members ?  Certainly passing 9-10 members is a tiresome and error-prone process. So in such cases instead of passing members individually, we can pass structure variable itself.
  • 7.
    #include<stdio.h> /*structure is definedabove all functions so it is global. */ struct student { char name[20]; char name[20]; int roll_no; int marks; }; void print_struct(struct student stu);
  • 8.
    OUTPUT Name: George Roll no:10 Marks: 69 int main() { struct student stu = {"George", 10, 69}; print_struct(stu); return 0; Marks: 69 return 0; } void print_struct(struct student stu){ printf("Name: %sn", stu.name); printf("Roll no: %dn", stu.roll_no); printf("Marks: %dn", stu.marks); printf("n"); }
  • 9.
     Although passingstructure variable as an argument allows us to pass all the members of the structure to a function there are some downsides to this operation.  Recall that a copy of the structure is passed to the formal argument.  Recall that a copy of the structure is passed to the formal argument. If the structure is large and you are passing structure variables frequently then it can take quite a bit of time which make the program inefficient.  Additional memory is required to save every copy of the structure.
  • 10.
    #include<stdio.h> /*structure is definedabove all functions so it is global. */ struct employee { { char name[20]; int age; char doj[10]; // date of joining char designation[20]; }; void print_struct(struct employee *);
  • 11.
    int main() { struct employeedev = {"Jane", 25, "25/2/2015", "Developer"}; print_struct(&dev); return 0; } } void print_struct(struct employee *ptr) { printf("Name: %sn", ptr->name); printf("Age: %dn", ptr->age); printf("Date of joining: %sn", ptr->doj); printf("Age: %sn", ptr->designation); printf("n"); }
  • 12.
     To returna structure from a function we must specify the appropriate return type in the function definition and declaration. struct player check_health(struct player p); { { ... }  This function accepts an argument of type struct player and returns an argument of type struct player.
  • 13.
    #include<stdio.h> /*structure is definedabove all functions so it is global. */ struct player { void print_struct(struct player p); struct player deduct_fees(struct player p); int main() { char name[20]; float height; float weight; float fees; }; int main() { struct player p = {"Joe", 5.9, 59, 5000 }; print_struct(p); p = deduct_fees(p); print_struct(p); return 0; }
  • 14.
    struct player deduct_fees(structplayer p) { p.fees -= 1000; return p; } OUTPUT Name: Joe Height: 5.90 Weight: 59.00 } void print_struct(const struct player p) { printf("Name: %sn", p.name); printf("Height: %.2fn", p.height); printf("Weight: %.2fn", p.weight); printf("Fees: %.2fn", p.fees); printf("n"); } Weight: 59.00 Fees: 5000.00 Name: Joe Height: 5.90 Weight: 59.00 Fees: 4000.00
  • 15.
     Structures inFunctions  Pointers to structures  Accessing structure members  Using pointer as a function argument Array of structures  Array of structures  Self referential structures.
  • 16.
     A pointerto a structure must be defined before it is pointed to a structure variable struct student { char name[50]; char name[50]; int age; }s1={"Sanju",12}; struct student *p; p = &s1; //p points to
  • 17.
     Structures inFunctions  Pointers to structures  Accessing structure members  Using pointer as a function argument  Array of structures  Array of structures  Self referential structures.
  • 18.
     The structuremembers can be accessed in three ways; two of them use a pointer with standard and special notation.  rect1.length //The standard access mechanism that doesn’t use a pointer. a pointer.  (*p).length //Pointer dereferenced with * and then connected to the member.  p->length //Uses a special operator, ->, that works only with structures.
  • 19.
     The structuremembers can be accessed in three ways; two of them use a pointer with standard and special notation. //The standard access mechanism that doesn’t use a pointer. printf("Name: %sn", s1.name); printf("Age: %dn", s1.age); printf("Age: %dn", s1.age); //Pointer dereferenced with * and then connected to the member. printf("Name: %sn",(*p).name); printf("Age: %dn", (*p).age); //Uses a special operator, ->, that works only with structures. printf("Name: %sn",p->name); printf("Age: %dn", p->age);
  • 20.
    #include <stdio.h> #include <string.h> intmain(void) { struct employee { short id; char name[30]; int pay; int pay; } emp = {1024, “Steve Wozniak”, 10000}, *p; p = &emp; printf(“Emp-id: %hd, Name: %s, Pay: %dn”, emp.id, (*p).name, p->pay); (*p).id = 4201; /* Updates id */ strcpy(p->name, “Steve Jobs”); /* Updates name */ p->pay = 20000; /* Updates pay */ printf(“Emp-id: %hd, Name: %s, Pay: %dn”, p->id, p->name, p->pay); return 0; }
  • 21.
    Output: Emp-id: 1024, Name:Steve Wozniak, Pay: 10000 Emp-id: 4201, Name: Steve Jobs, Pay: 20000
  • 22.
     Structures inFunctions  Pointers to structures  Accessing structure members  Using pointer as a function argument  Array of structures  Array of structures  Self referential structures.
  • 23.
     A structurevariable can be passed as function arguments  This will behave as pass-by-value.  This mechanism is safe and it protects the original structure from modification by the function. from modification by the function.  However, large structures can consume a lot of memory, so we may need to pass a pointer to a structure instead of the entire structure.  Updating a member’s value using a pointer represents a memory-efficient technique because the function copies not the structure (36 bytes) but its pointer (4 bytes).
  • 24.
    /* update_pay.c: Usesa pointer to a structure as a function argument to update the structure. */ #include <stdio.h> struct employee { short id; char name[30]; int pay; } emp = {1024, “Steve Wozniak”, 10000}; void update_pay(struct employee *f_emp, int f_pay); int main(void) { printf(“Old pay = %dn”, emp.pay); update_pay(&emp, 20000); printf(“New pay = %dn”, emp.pay); return 0; }
  • 25.
    void update_pay(struct employee*f_emp, int f_pay) { f_emp->pay = f_pay; /* Updates member pay of emp */ } OUTPUT: Old pay = 10000 New pay = 20000
  • 26.
     Structures inFunctions  Pointers to structures  Accessing structure members  Using pointer as a function argument  Array of structures  Array of structures  Self referential structures.
  • 27.
     We usedtwo structure variables, stud1 and stud2, to handle data of two students.  This technique won’t work with 500 students.  C supports an array of structures, whose definition may or may not be combined with the declaration of the structure.  The following statement defines an array of type struct student that can hold 50 sets (or records) of student data. that can hold 50 sets (or records) of student data.
  • 28.
     Alternatively, youcan separate the declaration and definition.  You can also use typedef to replace struct student with STUDENT.  Because stud is an array, its elements are laid out contiguously in memory.  The size of each array element is equal to the size of the structure in memory after accounting for slack bytes.  Pointer arithmetic can easily be employed here to access each array element, and using a special notation (->)
  • 29.
     This arraycan be partially or fully initialized by enclosing the initializers for each array element in a set of curly braces.  Each set is separated from its adjacent one by a comma, while the entire set of initializers are enclosed by outermost braces:
  • 30.
     Each memberof each element of this array is accessed by using a dot to connect the member to its array element.  You can use scanf to input values to each member using pointers to these variables (like &stud[i].marks).  A simple for loop using the array index as the key variable prints the entire list
  • 31.
    #include <stdio.h> #include <string.h> structstudent { int id; char name[30]; float percentage; }; }; int main() { int i; struct student record[2]; // 1st student's record record[0].id=1; strcpy(record[0].name, "Raju"); record[0].percentage = 86.5;
  • 32.
    // 2nd student'srecord record[1].id=2; strcpy(record[1].name, "Surendren"); record[1].percentage = 90.5; // 3rd student's record record[2].id=3; strcpy(record[2].name, "Thiyagu"); record[2].percentage = 81.5; record[2].percentage = 81.5; for(i=0; i<3; i++) { printf(" Records of STUDENT : %d n", i+1); printf(" Id is: %d n", record[i].id); printf(" Name is: %s n", record[i].name); printf(" Percentage is: %fnn",record[i].percentage); } return 0; }
  • 33.
    OUTPUT: Records of STUDENT: 1 Id is: 1 Name is: Raju Percentage is: 86.500000 Records of STUDENT : 2 Id is: 2 Id is: 2 Name is: Surendren Percentage is: 90.500000 Records of STUDENT : 3 Id is: 3 Name is: Thiyagu Percentage is: 81.500000
  • 34.
     Structures inFunctions  Pointers to structures  Accessing structure members  Using pointer as a function argument  Array of structures  Array of structures  Self referential structures
  • 35.
     A structurecan have members which point to a structure variable of the same type.  These types of structures are called self referential structures and are widely used in dynamic data structures like trees, linked list, etc.  Syntax to define self referential structure struct node { --- --- --- struct node *next; }; Here, next is a pointer to a struct node variable.  It should be remembered that a pointer to a structure is similar to a pointer to any other variable  A self referential data structure is essentially a structure definition which includes at least one member that is a pointer to the structure of its own kind.
  • 36.
    struct student { char name[20]; introll; char gender; int marks[5]; struct student *next; };  This is a self-referential structure where next is a struct student type structure pointer.  We will now create two structure variables stu1 and stu2 and initialize them with values.  We will then store the address of stu2 in next member of stu1.
  • 37.
    void main() { struct studentstu1 = {"Alex", 43, 'M', {76, 98, 68, 87, 93}, NULL}; struct student stu2 = { "Max", 33, 'M', {87, 84, 82, 96, 78}, NULL}; stu1.next = &stu2; } }
  • 38.
     We cannow access the members of stu2 using stu1 and next void main() { printf("Name: %sn", stu1.next->name); printf("Roll: %dn", stu1.next->roll); printf("Roll: %dn", stu1.next->roll); printf("Gender: %cn", stu1.next->gender); for(int i = 0; i < 5; i++) printf("Marks in %dth subject: %dn",i,stu1.next->marks[i]); }
  • 39.
     OUTPUT Name: Max Roll:33 Gender: M Gender: M Marks in 0th subject: 87 Marks in 1th subject: 84 Marks in 2th subject: 82 Marks in 3th subject: 96 Marks in 4th subject: 78
  • 40.
     Suppose wewant a different structure variable after stu1, that is insert another structure variable between stu1 and stu2. This can be done easily. void main() { struct student stu3 = { "Gasly", 23, 'M', {83, 64, 88, 79, 91}, NULL}; NULL}; st1.next = &stu3; stu3.next = &stu2; }
  • 41.
     Now stu1.nextstores the address of stu3. And stu3.next has the address of stu2. We can now access all three structures using stu1. printf("Roll Of %s: %dn", stu1.next->name, stu1.next->roll); printf("Gender Of %s: %cn", stu1.next->next->name, stu1.next->next->gender); stu1.next->next->gender);  OUTPUT Roll Of Gasly: 23 Gender Of Max: M