SlideShare a Scribd company logo
CHAPTER 1
a
253
;
int
adoes
~
a(n)
&
Jazu]
Structures
Structure is a user-defined data type of C++ to
represent a collection of logically related data items, which
may be of different types, under a common name.
Arrays allow to define type of variables that
can hold several data items of the same kind.
Similarly structure is another user defined data type
available in C++ that allows to combine data items of
different kinds.
• Structure is a user defined data type
• It is a collection of heterogeneous data items
• It can be defined using the key word STRUCT
-
- -
-
- -
Defining a Structure
To define a structure, you must use the struct statement. The struct statement
defines a new data type, with more than one member. The format of the struct
statement is as follows −
struct structure tag
{
data_type variable;
data_type variable;
data_type variable;
……………………………..
……………………………..
data_type variable;
} [one or more structure variables];
-
-
↑
T
-
Y
-
⑭
--
x
Eg:-
Struct student
{
int adm_no;
char name[20];
char group[20];
float fee;
};
-
-
-
-
-
-
e
Struct date
{
int dd;
int mm;
int yy;
};
-
-
-
Struct strdate
{
int day;
char month[10];
int year;
};
-
-
=
-
Variable declaration and memory allocation
Structure variable can be declared by the syntax:-
Struct structure-name structure-variable;
struct structure_tag var1, var2, ..., varN;
or
structure_tag var1, var2, ..., varN;
D -
-
-
- -
& - -
Eg:
Struct student s;
Student s;
↑
I
↑
-
date dob, today; OR struct date dob,
today;
strdate adm_date, join_date;
↓
↓ ↓
-
-
-
.
-
↑ T
Memory allocation of structure
variable
A C++ compiler allocate separate memory location for
each and every structure members.
struct student
{
Int roll_no;
Char name[20];
Float mark;
};
Total 28 bytes
Roll_no 4 byte
Name 20*1=20 byte
Mark 4 byte
I
-
&
Rollno
-
- name
mark
5
- -
-
- -
-
Variable initialisation
structure_tag variable={value1, value2,..., valueN};
Eg :
student s={3452, "Vaishakh", "Science", 270.00};
↓ ↓ I
- - -
-
----
si
sti
&
= - - -
Accessing elements of structure
The structure member can be accessed by using the
structure variable with dot(.) operator.
structure_variable.element_name
s.roll_no=5;
s.name=“abc”;
-
--
-
-
Write a c++ programme to read and print a student details
using structure.
Using namespace
std ;
[
# include <io stream
I
int main (7
Struct student Struct Student S ;
E contenter
Molno" ;
int colno ;
(in S .
colno ;
[20] ; "Inter the name" ;
char name
Cout
L
int age ;
S .
name
(in >>
3 ·
Coul" Enter the age";
(in> S .
age;
couts The student details are";
Cout" Rollno =
"LLS .
colno ;
Conti" Name =
"S .
name ;
Cout" Age =
"LLS .
age ;
turn 0
;
se
3
Nested structure
It means structure with in a structure and inner most
member in a nested structure can be accessed by chaining
all the conserved structure
Variable [outer most to inner most] with member using dot
operator (.)
Struct pay
{
Int basic;
Int da;
};
Struct employ
{
Int id;
Char name[10];
Struct pay p;
}
Void main()
{
Struct employ e;
e.id=101;
e.name=“abc”;
e.p.basic=10000;
e.p.da=101.5;
}
1-
g
-
-
g D
asic
C -
Po
zai
-
p
-
2
:
Elles
student s = {4325, "Vishal", {10, 11, 1997}, 575};
cout<<s.adm_no<<s.name;
cout<<s.dt_adm.day<<"/"<<s.dt_adm.month<<"/"<<s.dt_adm.year;
↓ ↓ ↓L ↓
- -
-
- -
&
adm adm
.
day ;
di y
.
al
da ;
e .
P
.
outer_structure_varaiable.inner_structure_variable.element
↑
IT 41
↑
da;
2
. p
.
Array Vs Structure
255
o
X
-M
- -
~ -
- -
so]
- -
- -
u
27 -
-
-
a
z
a
[2] -
-
-
aqu
E
Structures and pointers-2_240731_192519.pdf
Pointer
A pointer is a derived data type.
→It contain memory address of another variable.
→It can be used to access & manipulate data stored in
the memory.
lis
-
-
Benefits of pointers
• Pointers are more efficient in handling arrays.
• Pointers can be used to return multiple values from a function.
• Pointers support dynamic memory management.
• Pointers provide an efficient tool for manipulating dynamic data
structures such as data structures linked list , queue.
• Pointers reduced length and complexity of a programme.
• Pointers increases the execution speed.
-
-
-
-
-
- - -
-
-
int num=25;
a
&
A
I
----
variable is associated with two values :
L-value and R-value,
where L-value is the address of the variable and R-value is
its content.
Figure 1.5 shows that L-value of num is 1001 and R-value is 25
a
=
10 a 10110
-
=
-)
-
10110)
L
=
10
R
=
Declaring pointer variable
The declaration of a pointer variable take the following forms,
Data type * pointer_variable_name;
Eg:
int *p;
int *ptr1;
float *ptr2;
struct student *ptr3;
X
--
• The address of a variable can be assigned to pointer
variable using address operator (&)
Eg:
int *p;
int a;
p=&a
-
&
=
dai
=>
I
ptr1 = & num;
=
=
cout<< &num;
cout<< ptr1;
cout<< num;
cout<< *ptr1;
cout<< &ptr1;
cout<< *num;
-
&
-
-
cout<< &num; // 1001 (address of num) will be the output
cout<< ptr1; // 1001 (content of ptr1) will be the output
cout<< num; // 25 (content of num) will be the output
cout<< *ptr1; /* 25 (value in the location pointed to by
ptr1) will be the output */
cout<< &ptr1; // 1500 (address of ptr1) will be the output
cout<< *num; // Error!! num is not a pointer
=>
-
-
- -
-
--
-
-
The process of assigning address of a variable is known
as initialization.
initialization:- int a;
int *p=&a;
A pointer can store address of similar variable only.
Eg:- int *p;
float f;
p=&f /error
Y
-
-
-
of i
- p
=
-
-
• It is possible to make a pointer to another pointer. Thus
creating the chain of pointers.
Int x,*p1,**p2;
X=100;
P1=&x;
P2=&p1
COUT<<**p2;
-
* PI
↓
12
*
-
-
-
• A pointer can be initialized with null or zero.
• Multiplication is not possible on pointer variable.
-
Methods Of Memory Allocation
→The memory allocation that takes place before the execution
of the program is known as static memory allocation.
→memory is allocated during the execution of the program is
called dynamic memory allocation.
❑New : allocate
❑delete : de-allocate
-
-
-
-
Dynamic operators - new and delete
The operator new is a keyword in C++ and it triggers the
allocation of memory during run-time (execution).
following syntax is used for dynamic memory allocation:
pointer_variable = new data_type;
↑ ↑T
short * si_ptr;
float * fl_ptr;
struct complex * cx_ptr;
si_ptr = new short;
fl_ptr = new float;
cx_ptr = new complex;
--
-
-
- -
- -
-
-
- -
allocated memory locations can also be initialised using
the following syntax:
pointer_variable = new data_type(value);
The following examples show initialisation along with
dynamic memory allocation:
si_ptr = new short(0);
fl_ptr = new float(3.14);
-
- - -
-
O
.
14
-
-
-
S 3
-
-
- -
-
delete operator is used with the following
Syntax :
delete pointer_variable;
The following are valid examples:
delete si_ptr;
delete fl_ptr, cx_ptr;
-
-
- -
--
Memory leak
Orphaned Memory Block
If the memory allocated using new operator is not freed
using delete, that memory is said to be an orphaned memory
block
- a block of memory that is left unused, but not released for
further allocation. This memory block is allocated on each
execution of the program and the size of the orphaned block is
increased. Thus a part of the memory seems to disappear on
every run of the program, and eventually the amount of
memory consumed has an unfavorable effect. This situation is
known as memory leak.
New
-
-
-
The following are the reasons for memory leak :
• Forgetting to delete the memory that has been allocated
dynamically (using new).
• Failing to execute the delete statement due to poor logic of
the program code.
• Assigning the address returned by new operator to a pointer
that was already pointing to an allocated object
-
- -
-
-
~
-
-
-
-
-
Operations on pointers
The operators that can be used with pointers and how these
operations are performed.
Arithmetic operations on pointers
si_ptr and fl_ptr
= -
----
-
-
cout << si_ptr + 1;
cout << fl_ptr + 1;
What will be the output? Do you think that it will be 1001 and 1011?
-
0
1000 &
O - 1000
+
&
/ 100l ⑪
- -
When we add 1 to a short int pointer, the expression returns the address of the
next location of short int type.
si_ptr+1
(1000+(1*2))=1002 (size of short int is 2 bytes)
fl_ptr+1
(1010+(1*4))=1014 (size of float is 4 byte)
si_ptr+5=?
-
-
- - -
1000 + 5x2
= 1010
2
si_ptr+5 = (1000+5×2)=1010
fl_ptr+3 = (1010+3×4)=1022
This kind of operation is practically wrong.
T
↓
-
--
Because we are trying to access locations that are
not allocated for authorised use. These locations might
have been used by some other variables. Sometimes
these locations might not have been accessible due to
the violation of access rights.
→No other arithmetic operations are performed on
pointers
pointers are only incremented or decremented
-
int *ptr1, *ptr2; // Declaration of two integer pointers
ptr1 = new int(5); /* Dynamic memory allocation (let the
address be 1000)and initialization with 5*/
ptr2 = ptr1 + 1; /* ptr2 will point to the very next
integer location with the address 1004 */
++ptr2; // Same as ptr2 = ptr2 + 1
-
-
-
nau)
-
1000
look//
I
We used arrays in such a situation. But the size should be
specified during the array declaration. This may cause
wastage or insufficiency of memory space.
Pointer and its arithmetic overcome this drawback.
---
:
11:
x
- -
But there is a problem in this kind of memory usage. It is not
sure that Program 1.3 will always run with any value of n.
pointer ht_ptr is initialised with the address of only one
location. The memory locations accessed using pointer
arithmetic on ht_ptr are unauthorised, since these locations
are not allocated by the OS.
We can overcome these issues by the facility of dynamic
arrays, -
-
Relational operations on pointers
Among the six relational operators, only == (equality) and
!= (non-equality) operators are used with pointers.
If p and q are two pointers, they may contain the address of
the same integer location or different memory locations.
This can be verified with the expressions
p==q or p!=q
- - -
T
-
& Fr
E
Pointer and array
Figure 1.9 shows the memory allocation of an array ar[10]
of int type with 10 numbers.
-
aso
&
j
[]
Gab
Cr23]
I
:
crai)
-
If ptr is an integer pointer
ptr = &ar[0];
autos
;
T
&
Pla
cout<<ptr; //Displays 1000, the address of ar[0]
cout<<*ptr; //Displays 34, the value of ar[0]
cout<<(ptr+1); //Displays 1004, the address of ar[1]
cout<<*(ptr+1); //Displays 12, the value of ar[1]
cout<<(ptr+9); //Displays 1036, the address of ar[9]
cout<<*(ptr+9); //Displays 19, the value of ar[9]
U
-
-
-
*
X
-
-
10
-
-
-
-
a4
-
A
-
-
I
-
1
6
- T
-
Can you predict the output of the statement :
cout<<ar;
output will be 1000
The address of the first location of the array
-
P as
-
The following C++ statement displays all the elements of
this array :
for (int i=0; i<10; i++)
cout<<*(ar+i)<<'t';
-
There is a difference between an ordinary pointer and an
array-name.
ptr++; is valid and is equivalent to ptr=ptr+1;
The statement ar++; is invalid,
Because array-name always contains the base
address of the array, and it cannot be changed.
z
D
3
&
z
D
z
&
- -
y
a
-
Dynamic array
Dynamic array is created during run time using
the dynamic memory allocation operator new.
The syntax is:
pointer = new data_type[size];
↓
-
-
is
Array of strings
A array or character pointer can be used to
store only one name at a time. Here we need to refer to a
collection of strings ("Sunday", "Monday", ..., "Saturday“)
The following statement declares an array of
character pointers to handle this case:
char *name[7];
This array can contain a maximum of 7 strings,
where each string can contain any number of characters.
char *week[7]={"Sunday", "Monday", "Tuesday",
"Wednesday",
"Thursday", "Friday", "Saturday"};
& & &
----- ----- ------
&
-
- -
-
---y) /
& ⑮ B
-
[2
v
-
- -
·
Pointer and structure
structures are accessed by pointers. A structure
is defined to represent the details of employees as follows:
struct employee
{
int ecode;
char ename[15];
float salary;
};
-
-
-
employee *eptr ;
* eptr · ecode ;
Y
-
salary ;
1a-7
de ; ep
epto
-
>
eco
encue ;
-
>
epto
It is clear that eptr is a pointer that can hold the address of
employee type data. The statement:
eptr = new employee;
-
-
structure is accessed in terms of its elements with the following
format : structure_variable.element_name
have to use the pointer eptr. The syntax for accessing the
elements of a structure is as follows:
structure_pointer->element_name
-
C .
id ;
e .
name
;
-
-
--
Self referential structure
Self referential structure is a structure in which one of the
elements is a pointer to the same structure.
Self referential structure is a powerful tool of C and C++
languages that helps to develop dynamic data structures
like linked list, tree, etc
The memory locations are scattered, but there will be
a link from one location to another
-
-
struct Noch
E
int
data ;
Node * next ;
-
3;
Structures and pointers-2_240731_192519.pdf

More Related Content

PDF
C++_notes.pdf
PPT
C1320prespost
PDF
Memory Management for C and C++ _ language
PPTX
pointers in c programming - example programs
PDF
Chapter 5 (Part I) - Pointers.pdf
PPT
Pointers - DataStructures
PPT
Unit 6 pointers
PPT
Pointer
C++_notes.pdf
C1320prespost
Memory Management for C and C++ _ language
pointers in c programming - example programs
Chapter 5 (Part I) - Pointers.pdf
Pointers - DataStructures
Unit 6 pointers
Pointer

Similar to Structures and pointers-2_240731_192519.pdf (20)

PDF
Linked list
PPTX
Introduction to dynamic memory allocation – Structures–accessing structure me...
PPTX
C Programming Unit-4
DOCX
DS UNIT3_LINKED LISTS.docx
PPTX
Chapter 2 part II array and structure.pptx
PDF
c programming
PPT
Computer Programming- Lecture 7
PPTX
Dynamic Memory Allocation.pptx
PPTX
BBACA-SEM-III-Datastructure-PPT(0) for third semestetr
PDF
Object Oriented Programming (OOP) using C++ - Lecture 5
DOCX
08-Pointers.docx An array is a linear data structure
PPT
Link list
PPT
ch08.ppt
PDF
Lk module5 pointers
PPTX
Pointers in c
PPTX
CHAPTER -4-class and structure.pptx
PPTX
Structures_and_Files[1] - Read-Only.pptx
PPT
Lecture2.ppt
PPTX
Pointers and Memory Allocation ESC101.pptx
PDF
03 structures
Linked list
Introduction to dynamic memory allocation – Structures–accessing structure me...
C Programming Unit-4
DS UNIT3_LINKED LISTS.docx
Chapter 2 part II array and structure.pptx
c programming
Computer Programming- Lecture 7
Dynamic Memory Allocation.pptx
BBACA-SEM-III-Datastructure-PPT(0) for third semestetr
Object Oriented Programming (OOP) using C++ - Lecture 5
08-Pointers.docx An array is a linear data structure
Link list
ch08.ppt
Lk module5 pointers
Pointers in c
CHAPTER -4-class and structure.pptx
Structures_and_Files[1] - Read-Only.pptx
Lecture2.ppt
Pointers and Memory Allocation ESC101.pptx
03 structures
Ad

Recently uploaded (20)

PPT
Project quality management in manufacturing
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PPTX
UNIT 4 Total Quality Management .pptx
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
Construction Project Organization Group 2.pptx
PPTX
Geodesy 1.pptx...............................................
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
additive manufacturing of ss316l using mig welding
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
web development for engineering and engineering
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Project quality management in manufacturing
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
UNIT 4 Total Quality Management .pptx
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Construction Project Organization Group 2.pptx
Geodesy 1.pptx...............................................
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
CH1 Production IntroductoryConcepts.pptx
bas. eng. economics group 4 presentation 1.pptx
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
additive manufacturing of ss316l using mig welding
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
web development for engineering and engineering
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Ad

Structures and pointers-2_240731_192519.pdf

  • 3. Structures Structure is a user-defined data type of C++ to represent a collection of logically related data items, which may be of different types, under a common name. Arrays allow to define type of variables that can hold several data items of the same kind. Similarly structure is another user defined data type available in C++ that allows to combine data items of different kinds. • Structure is a user defined data type • It is a collection of heterogeneous data items • It can be defined using the key word STRUCT - - - - - -
  • 4. Defining a Structure To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member. The format of the struct statement is as follows − struct structure tag { data_type variable; data_type variable; data_type variable; …………………………….. …………………………….. data_type variable; } [one or more structure variables]; - - ↑ T - Y - ⑭ -- x
  • 5. Eg:- Struct student { int adm_no; char name[20]; char group[20]; float fee; }; - - - - - - e
  • 6. Struct date { int dd; int mm; int yy; }; - - -
  • 7. Struct strdate { int day; char month[10]; int year; }; - - = -
  • 8. Variable declaration and memory allocation Structure variable can be declared by the syntax:- Struct structure-name structure-variable; struct structure_tag var1, var2, ..., varN; or structure_tag var1, var2, ..., varN; D - - - - - & - -
  • 10. date dob, today; OR struct date dob, today; strdate adm_date, join_date; ↓ ↓ ↓ - - - . - ↑ T
  • 11. Memory allocation of structure variable
  • 12. A C++ compiler allocate separate memory location for each and every structure members. struct student { Int roll_no; Char name[20]; Float mark; }; Total 28 bytes Roll_no 4 byte Name 20*1=20 byte Mark 4 byte I - & Rollno - - name mark 5
  • 14. Variable initialisation structure_tag variable={value1, value2,..., valueN}; Eg : student s={3452, "Vaishakh", "Science", 270.00}; ↓ ↓ I - - - - ----
  • 16. Accessing elements of structure The structure member can be accessed by using the structure variable with dot(.) operator. structure_variable.element_name s.roll_no=5; s.name=“abc”; - -- - -
  • 17. Write a c++ programme to read and print a student details using structure. Using namespace std ; [ # include <io stream I int main (7 Struct student Struct Student S ; E contenter Molno" ; int colno ; (in S . colno ; [20] ; "Inter the name" ; char name Cout L int age ; S . name (in >> 3 ·
  • 18. Coul" Enter the age"; (in> S . age; couts The student details are"; Cout" Rollno = "LLS . colno ; Conti" Name = "S . name ; Cout" Age = "LLS . age ; turn 0 ; se 3
  • 19. Nested structure It means structure with in a structure and inner most member in a nested structure can be accessed by chaining all the conserved structure Variable [outer most to inner most] with member using dot operator (.)
  • 20. Struct pay { Int basic; Int da; }; Struct employ { Int id; Char name[10]; Struct pay p; } Void main() { Struct employ e; e.id=101; e.name=“abc”; e.p.basic=10000; e.p.da=101.5; } 1- g - - g D asic C - Po zai - p - 2 :
  • 21. Elles
  • 22. student s = {4325, "Vishal", {10, 11, 1997}, 575}; cout<<s.adm_no<<s.name; cout<<s.dt_adm.day<<"/"<<s.dt_adm.month<<"/"<<s.dt_adm.year; ↓ ↓ ↓L ↓ - - - - - & adm adm . day ; di y . al da ; e . P .
  • 24. Array Vs Structure 255 o X -M - - ~ - - - so] - - - - u 27 - - - a z a [2] - - - aqu E
  • 26. Pointer A pointer is a derived data type. →It contain memory address of another variable. →It can be used to access & manipulate data stored in the memory. lis - -
  • 27. Benefits of pointers • Pointers are more efficient in handling arrays. • Pointers can be used to return multiple values from a function. • Pointers support dynamic memory management. • Pointers provide an efficient tool for manipulating dynamic data structures such as data structures linked list , queue. • Pointers reduced length and complexity of a programme. • Pointers increases the execution speed. - - - - - - - - - -
  • 29. variable is associated with two values : L-value and R-value, where L-value is the address of the variable and R-value is its content. Figure 1.5 shows that L-value of num is 1001 and R-value is 25 a = 10 a 10110 - = -) - 10110) L = 10 R =
  • 30. Declaring pointer variable The declaration of a pointer variable take the following forms, Data type * pointer_variable_name; Eg: int *p; int *ptr1; float *ptr2; struct student *ptr3; X --
  • 31. • The address of a variable can be assigned to pointer variable using address operator (&) Eg: int *p; int a; p=&a - & = dai => I
  • 32. ptr1 = & num; = =
  • 33. cout<< &num; cout<< ptr1; cout<< num; cout<< *ptr1; cout<< &ptr1; cout<< *num; - & - -
  • 34. cout<< &num; // 1001 (address of num) will be the output cout<< ptr1; // 1001 (content of ptr1) will be the output cout<< num; // 25 (content of num) will be the output cout<< *ptr1; /* 25 (value in the location pointed to by ptr1) will be the output */ cout<< &ptr1; // 1500 (address of ptr1) will be the output cout<< *num; // Error!! num is not a pointer => - - - - - -- - -
  • 35. The process of assigning address of a variable is known as initialization. initialization:- int a; int *p=&a; A pointer can store address of similar variable only. Eg:- int *p; float f; p=&f /error Y - - - of i - p = - -
  • 36. • It is possible to make a pointer to another pointer. Thus creating the chain of pointers. Int x,*p1,**p2; X=100; P1=&x; P2=&p1 COUT<<**p2; - * PI ↓ 12 * - - -
  • 37. • A pointer can be initialized with null or zero. • Multiplication is not possible on pointer variable. -
  • 38. Methods Of Memory Allocation →The memory allocation that takes place before the execution of the program is known as static memory allocation. →memory is allocated during the execution of the program is called dynamic memory allocation. ❑New : allocate ❑delete : de-allocate - - - -
  • 39. Dynamic operators - new and delete The operator new is a keyword in C++ and it triggers the allocation of memory during run-time (execution). following syntax is used for dynamic memory allocation: pointer_variable = new data_type; ↑ ↑T
  • 40. short * si_ptr; float * fl_ptr; struct complex * cx_ptr; si_ptr = new short; fl_ptr = new float; cx_ptr = new complex; -- - - - - - - -
  • 41. - - -
  • 42. allocated memory locations can also be initialised using the following syntax: pointer_variable = new data_type(value); The following examples show initialisation along with dynamic memory allocation: si_ptr = new short(0); fl_ptr = new float(3.14); - - - - - O . 14 - - - S 3 - - - - -
  • 43. delete operator is used with the following Syntax : delete pointer_variable; The following are valid examples: delete si_ptr; delete fl_ptr, cx_ptr; - - - - --
  • 44. Memory leak Orphaned Memory Block If the memory allocated using new operator is not freed using delete, that memory is said to be an orphaned memory block - a block of memory that is left unused, but not released for further allocation. This memory block is allocated on each execution of the program and the size of the orphaned block is increased. Thus a part of the memory seems to disappear on every run of the program, and eventually the amount of memory consumed has an unfavorable effect. This situation is known as memory leak. New - - -
  • 45. The following are the reasons for memory leak : • Forgetting to delete the memory that has been allocated dynamically (using new). • Failing to execute the delete statement due to poor logic of the program code. • Assigning the address returned by new operator to a pointer that was already pointing to an allocated object - - - - -
  • 47. Operations on pointers The operators that can be used with pointers and how these operations are performed.
  • 48. Arithmetic operations on pointers si_ptr and fl_ptr = - ---- - -
  • 49. cout << si_ptr + 1; cout << fl_ptr + 1; What will be the output? Do you think that it will be 1001 and 1011? - 0 1000 & O - 1000 + & / 100l ⑪ - -
  • 50. When we add 1 to a short int pointer, the expression returns the address of the next location of short int type. si_ptr+1 (1000+(1*2))=1002 (size of short int is 2 bytes) fl_ptr+1 (1010+(1*4))=1014 (size of float is 4 byte) si_ptr+5=? - - - - - 1000 + 5x2 = 1010 2
  • 51. si_ptr+5 = (1000+5×2)=1010 fl_ptr+3 = (1010+3×4)=1022 This kind of operation is practically wrong. T ↓ - --
  • 52. Because we are trying to access locations that are not allocated for authorised use. These locations might have been used by some other variables. Sometimes these locations might not have been accessible due to the violation of access rights. →No other arithmetic operations are performed on pointers pointers are only incremented or decremented -
  • 53. int *ptr1, *ptr2; // Declaration of two integer pointers ptr1 = new int(5); /* Dynamic memory allocation (let the address be 1000)and initialization with 5*/ ptr2 = ptr1 + 1; /* ptr2 will point to the very next integer location with the address 1004 */ ++ptr2; // Same as ptr2 = ptr2 + 1 - - - nau) - 1000 look// I
  • 54. We used arrays in such a situation. But the size should be specified during the array declaration. This may cause wastage or insufficiency of memory space. Pointer and its arithmetic overcome this drawback. --- : 11: x - -
  • 55. But there is a problem in this kind of memory usage. It is not sure that Program 1.3 will always run with any value of n. pointer ht_ptr is initialised with the address of only one location. The memory locations accessed using pointer arithmetic on ht_ptr are unauthorised, since these locations are not allocated by the OS. We can overcome these issues by the facility of dynamic arrays, - -
  • 56. Relational operations on pointers Among the six relational operators, only == (equality) and != (non-equality) operators are used with pointers.
  • 57. If p and q are two pointers, they may contain the address of the same integer location or different memory locations. This can be verified with the expressions p==q or p!=q - - - T - & Fr E
  • 58. Pointer and array Figure 1.9 shows the memory allocation of an array ar[10] of int type with 10 numbers. - aso & j [] Gab Cr23] I : crai) -
  • 59. If ptr is an integer pointer ptr = &ar[0]; autos ; T & Pla
  • 60. cout<<ptr; //Displays 1000, the address of ar[0] cout<<*ptr; //Displays 34, the value of ar[0] cout<<(ptr+1); //Displays 1004, the address of ar[1] cout<<*(ptr+1); //Displays 12, the value of ar[1] cout<<(ptr+9); //Displays 1036, the address of ar[9] cout<<*(ptr+9); //Displays 19, the value of ar[9] U - - - * X - - 10 - - - - a4 - A - - I - 1 6 - T -
  • 61. Can you predict the output of the statement : cout<<ar; output will be 1000 The address of the first location of the array - P as -
  • 62. The following C++ statement displays all the elements of this array : for (int i=0; i<10; i++) cout<<*(ar+i)<<'t'; -
  • 63. There is a difference between an ordinary pointer and an array-name. ptr++; is valid and is equivalent to ptr=ptr+1; The statement ar++; is invalid, Because array-name always contains the base address of the array, and it cannot be changed. z D 3 & z D z & - - y a -
  • 64. Dynamic array Dynamic array is created during run time using the dynamic memory allocation operator new. The syntax is: pointer = new data_type[size]; ↓ - - is
  • 65. Array of strings A array or character pointer can be used to store only one name at a time. Here we need to refer to a collection of strings ("Sunday", "Monday", ..., "Saturday“) The following statement declares an array of character pointers to handle this case: char *name[7];
  • 66. This array can contain a maximum of 7 strings, where each string can contain any number of characters. char *week[7]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; & & & ----- ----- ------ & - - - - ---y) / & ⑮ B - [2 v - - - ·
  • 67. Pointer and structure structures are accessed by pointers. A structure is defined to represent the details of employees as follows: struct employee { int ecode; char ename[15]; float salary; }; - - -
  • 68. employee *eptr ; * eptr · ecode ; Y - salary ; 1a-7 de ; ep epto - > eco encue ; - > epto
  • 69. It is clear that eptr is a pointer that can hold the address of employee type data. The statement: eptr = new employee; -
  • 70. -
  • 71. structure is accessed in terms of its elements with the following format : structure_variable.element_name have to use the pointer eptr. The syntax for accessing the elements of a structure is as follows: structure_pointer->element_name - C . id ; e . name ; - - --
  • 72. Self referential structure Self referential structure is a structure in which one of the elements is a pointer to the same structure.
  • 73. Self referential structure is a powerful tool of C and C++ languages that helps to develop dynamic data structures like linked list, tree, etc The memory locations are scattered, but there will be a link from one location to another - - struct Noch E int data ; Node * next ; - 3;