Structures in Functions discusses pointers to structures, accessing structure members, passing structures as function arguments by value and by reference, returning structures from functions, arrays of structures, and self-referential structures. Key points include passing a pointer to a structure as a function argument to avoid copying large structures, defining an array of structures to store multiple records, and using a pointer as a member of a structure to create self-referential linked structures like linked lists.
Discusses structures in functions, passing structures, and usage of pointers. Highlights passing structure members and variables, alongside memory efficiency concerns.
Focuses on using pointers for structure functions, showing return types and function declarations for efficiency when working with larger structures.
Illustrates pointer dereferencing techniques for structures, explaining access mechanisms and demonstrating with example structures.
Describes memory-efficient passing of structures by reference, highlighting the trade-off between value and pointer mechanics in function arguments.
Introduces arrays of structures, memory layout and initialization techniques, with examples demonstrating data handling for multiple records.
Explores self-referential structures used in data structures like linked lists, providing examples of implementation and accessing nested structures.
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);
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 *);
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;
}
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);
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.
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