SlideShare a Scribd company logo
 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

More Related Content

What's hot

Python tuple
Python   tuplePython   tuple
Python tuple
Mohammed Sikander
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
bhavesh prakash
 
Pointers
PointersPointers
Pointers
sanya6900
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
ThamizhselviKrishnam
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
Harsh Pathak
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
Md. Ashraful Islam
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
channa basava
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
Wingston
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
amiable_indian
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
DevoAjit Gupta
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Rajat Busheheri
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
•sreejith •sree
 
Functions in C
Functions in CFunctions in C
Functions in C
Kamal Acharya
 
Array in c programming
Array in c programmingArray in c programming
Array in c programming
Mazharul Islam
 
4. plsql
4. plsql4. plsql
4. plsql
Amrit Kaur
 
C string
C stringC string
Functions in c
Functions in cFunctions in c
Functions in c
sunila tharagaturi
 

What's hot (20)

Python tuple
Python   tuplePython   tuple
Python tuple
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Pointers
PointersPointers
Pointers
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Array in c programming
Array in c programmingArray in c programming
Array in c programming
 
4. plsql
4. plsql4. plsql
4. plsql
 
C string
C stringC string
C string
 
Functions in c
Functions in cFunctions in c
Functions in c
 

Similar to Pointers and Structures

Easy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdfEasy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
sudhakargeruganti
 
structures.ppt
structures.pptstructures.ppt
structures.ppt
RamyaR163211
 
Introduction to structures in c lang.ppt
Introduction to structures in c lang.pptIntroduction to structures in c lang.ppt
Introduction to structures in c lang.ppt
shivani366010
 
C structure and union
C structure and unionC structure and union
C structure and union
Thesis Scientist Private Limited
 
Structure & union
Structure & unionStructure & union
Structure & union
lalithambiga kamaraj
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and Pointers
Prabu U
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing concepts
kavitham66441
 
User defined data types.pptx
User defined data types.pptxUser defined data types.pptx
User defined data types.pptx
Ananthi Palanisamy
 
VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4
YOGESH SINGH
 
Structures
StructuresStructures
Structures
archikabhatia
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
thenmozhip8
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
Unit 5 (1)
Unit 5 (1)Unit 5 (1)
Unit 5 (1)
psaravanan1985
 
Structures and Unions
Structures and UnionsStructures and Unions
Structures and Unions
Vijayananda Ratnam Ch
 
Structure in c language
Structure in c languageStructure in c language
Structure in c language
sangrampatil81
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University
 
Diploma ii cfpc- u-5.3 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.3 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.3 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.3 pointer, structure ,union and intro to file handling
Rai University
 
Structures
StructuresStructures
Structures
DrJasmineBeulahG
 
structure.ppt
structure.pptstructure.ppt
structure.ppt
Sheik Mohideen
 

Similar to Pointers and Structures (20)

Easy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdfEasy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
 
structures.ppt
structures.pptstructures.ppt
structures.ppt
 
Introduction to structures in c lang.ppt
Introduction to structures in c lang.pptIntroduction to structures in c lang.ppt
Introduction to structures in c lang.ppt
 
C structure and union
C structure and unionC structure and union
C structure and union
 
Structure & union
Structure & unionStructure & union
Structure & union
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and Pointers
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing concepts
 
User defined data types.pptx
User defined data types.pptxUser defined data types.pptx
User defined data types.pptx
 
VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4
 
Structures
StructuresStructures
Structures
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
 
Unit 5 (1)
Unit 5 (1)Unit 5 (1)
Unit 5 (1)
 
Structures and Unions
Structures and UnionsStructures and Unions
Structures and Unions
 
Structure in c language
Structure in c languageStructure in c language
Structure in c language
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Diploma ii cfpc- u-5.3 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.3 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.3 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.3 pointer, structure ,union and intro to file handling
 
Structures
StructuresStructures
Structures
 
C1320prespost
C1320prespostC1320prespost
C1320prespost
 
structure.ppt
structure.pptstructure.ppt
structure.ppt
 

More from Gem WeBlog

Analysis of optimization algorithms
Analysis of optimization algorithmsAnalysis of optimization algorithms
Analysis of optimization algorithms
Gem WeBlog
 
Particle swarm intelligence
Particle swarm intelligenceParticle swarm intelligence
Particle swarm intelligence
Gem WeBlog
 
Nature inspired metaheuristics
Nature inspired metaheuristicsNature inspired metaheuristics
Nature inspired metaheuristics
Gem WeBlog
 
Darwin's theory of evolution
Darwin's theory of evolutionDarwin's theory of evolution
Darwin's theory of evolution
Gem WeBlog
 
no free-lunch theorem
no free-lunch theoremno free-lunch theorem
no free-lunch theorem
Gem WeBlog
 
Video and animation
Video and animationVideo and animation
Video and animation
Gem WeBlog
 
Mpeg video compression
Mpeg video compressionMpeg video compression
Mpeg video compression
Gem WeBlog
 
Digital audio
Digital audioDigital audio
Digital audio
Gem WeBlog
 
Designing multimedia
Designing multimediaDesigning multimedia
Designing multimedia
Gem WeBlog
 
Testing and Rolling Out Enterprise Applications
Testing and Rolling Out Enterprise ApplicationsTesting and Rolling Out Enterprise Applications
Testing and Rolling Out Enterprise Applications
Gem WeBlog
 
Constructing Enterprise Applications
Constructing Enterprise  ApplicationsConstructing Enterprise  Applications
Constructing Enterprise Applications
Gem WeBlog
 
Architecting and Designing Enterprise Applications
Architecting and Designing Enterprise ApplicationsArchitecting and Designing Enterprise Applications
Architecting and Designing Enterprise Applications
Gem WeBlog
 
Incepting Enterprise Applications
Incepting Enterprise ApplicationsIncepting Enterprise Applications
Incepting Enterprise Applications
Gem WeBlog
 
Introduction to BEA
Introduction to BEAIntroduction to BEA
Introduction to BEA
Gem WeBlog
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Gem WeBlog
 
Function pointer
Function pointerFunction pointer
Function pointer
Gem WeBlog
 
10. NULL pointer
10. NULL pointer10. NULL pointer
10. NULL pointer
Gem WeBlog
 
13. Pointer and 2D array
13. Pointer  and  2D array13. Pointer  and  2D array
13. Pointer and 2D array
Gem WeBlog
 
12.string and pointer
12.string and pointer12.string and pointer
12.string and pointer
Gem WeBlog
 
7. Pointer Arithmetic
7. Pointer Arithmetic7. Pointer Arithmetic
7. Pointer Arithmetic
Gem WeBlog
 

More from Gem WeBlog (20)

Analysis of optimization algorithms
Analysis of optimization algorithmsAnalysis of optimization algorithms
Analysis of optimization algorithms
 
Particle swarm intelligence
Particle swarm intelligenceParticle swarm intelligence
Particle swarm intelligence
 
Nature inspired metaheuristics
Nature inspired metaheuristicsNature inspired metaheuristics
Nature inspired metaheuristics
 
Darwin's theory of evolution
Darwin's theory of evolutionDarwin's theory of evolution
Darwin's theory of evolution
 
no free-lunch theorem
no free-lunch theoremno free-lunch theorem
no free-lunch theorem
 
Video and animation
Video and animationVideo and animation
Video and animation
 
Mpeg video compression
Mpeg video compressionMpeg video compression
Mpeg video compression
 
Digital audio
Digital audioDigital audio
Digital audio
 
Designing multimedia
Designing multimediaDesigning multimedia
Designing multimedia
 
Testing and Rolling Out Enterprise Applications
Testing and Rolling Out Enterprise ApplicationsTesting and Rolling Out Enterprise Applications
Testing and Rolling Out Enterprise Applications
 
Constructing Enterprise Applications
Constructing Enterprise  ApplicationsConstructing Enterprise  Applications
Constructing Enterprise Applications
 
Architecting and Designing Enterprise Applications
Architecting and Designing Enterprise ApplicationsArchitecting and Designing Enterprise Applications
Architecting and Designing Enterprise Applications
 
Incepting Enterprise Applications
Incepting Enterprise ApplicationsIncepting Enterprise Applications
Incepting Enterprise Applications
 
Introduction to BEA
Introduction to BEAIntroduction to BEA
Introduction to BEA
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Function pointer
Function pointerFunction pointer
Function pointer
 
10. NULL pointer
10. NULL pointer10. NULL pointer
10. NULL pointer
 
13. Pointer and 2D array
13. Pointer  and  2D array13. Pointer  and  2D array
13. Pointer and 2D array
 
12.string and pointer
12.string and pointer12.string and pointer
12.string and pointer
 
7. Pointer Arithmetic
7. Pointer Arithmetic7. Pointer Arithmetic
7. Pointer Arithmetic
 

Recently uploaded

Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 

Recently uploaded (20)

Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 

Pointers and Structures

  • 1.
  • 2.  Structures in Functions  Pointers to structures  Accessing structure members  Using pointer as a function argument  Array of structures  Array of structures  Self referential structures.
  • 3.  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
  • 4. #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);
  • 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 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.
  • 7. #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);
  • 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 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.
  • 10. #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 *);
  • 11. 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"); }
  • 12.  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.
  • 13. #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; }
  • 14. 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
  • 15.  Structures in Functions  Pointers to structures  Accessing structure members  Using pointer as a function argument Array of structures  Array of structures  Self referential structures.
  • 16.  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
  • 17.  Structures in Functions  Pointers to structures  Accessing structure members  Using pointer as a function argument  Array of structures  Array of structures  Self referential structures.
  • 18.  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.
  • 19.  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);
  • 20. #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; }
  • 21. Output: Emp-id: 1024, Name: Steve Wozniak, Pay: 10000 Emp-id: 4201, Name: Steve Jobs, Pay: 20000
  • 22.  Structures in Functions  Pointers to structures  Accessing structure members  Using pointer as a function argument  Array of structures  Array of structures  Self referential structures.
  • 23.  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).
  • 24. /* 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; }
  • 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 in Functions  Pointers to structures  Accessing structure members  Using pointer as a function argument  Array of structures  Array of structures  Self referential structures.
  • 27.  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.
  • 28.  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 (->)
  • 29.  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:
  • 30.  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
  • 31. #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;
  • 32. // 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; }
  • 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 in Functions  Pointers to structures  Accessing structure members  Using pointer as a function argument  Array of structures  Array of structures  Self referential structures
  • 35.  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.
  • 36. 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.
  • 37. 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; } }
  • 38.  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]); }
  • 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 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; }
  • 41.  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