Structures & Pointers 2
Structures & Pointers 2
STRUCTURES
& POINTERS
Part 1
Contents
Structures
Variable declaration and memory allocation
Variable initialisation
Accessing elements of structure
Nested structure
Array Vs Structure
Structures
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.
E
struct structure tag
{
data_type variable;
data_type variable;
data_type variable;
……………………………..
……………………………..
data_type variable;
{
=
O
Struct student
int adm_no; -
- char name[20]; -
- char group[20]; -
float fee;
-
};
D
[insda,
struct daft Struct date
{ -
int dd;-
E - int mm;-
int yy;
};
inf
adj
-
date
Es
Inf
;
mm
-
inte
i
3 d
;
Struct date
{
int day;
char month[10];
int year;
};
Variable declaration and memory allocation
Structure variable can be declared by the syntax
-
structure_tag var1, var2, ..., varN;
- -
Eg:
Struct student s;
Student s;
date dob, today; struct date dob, today;
OR
strdate adm_date, join_date;
Memory allocation
of structure variable
A c++ compiler allocate separate memory location for each and every
structure members.
Int roll_no; ~ ,
Char name[20];
-
float-sbut h
Float mark;
- -
};--
Chur-Abste
=
-
Total 28 bytes
Roll_no 4 byte
Name 20*1=20 byte
Mark 4 byte 4 1x20 + 3
+ 20 + 3 =
EUby
day month[10] year
Eg:
= structure_variable.element_name
s.roll_no=5;
s.name=“abc”;
Struct Audezt
i
today.dd = 10;
E
-
int
strcpy(adm_date.month, "June");
cin >> s1.adm_no;
admung
cout << c1.real + c2.real;
float fe
;
D
-
inf
S .
admno
mosky
S
S ·
↑
fee
more
3
Write a c++ programme to read and print student details using structure.
Nested structure
i
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;
}
D
Definition A Definition B
cout<<s.dt_adm.day<<"/"<<s.dt_adm.month<<"/"<<s.dt_adm.year;
outer_structure_varaiable.inner_structure_variable.element
-
E
Arrays Structures
It is a derived data type. It is a user-defined data type
-
-
structure is formed.
Array of structures is possible.
-
Structure can contain arrays as
elements -
Chapter 1
STRUCTURES
& POINTERS
Part 2
Contents
Pointer
Benefits of pointers
Declaring pointer variable
Methods Of Memory Allocation
Dynamic operators
Memory leak
Pointers
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.
Pointer
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;
num 25
1001 1001 1001 1001
variable is associated with two values:
L-value and R-value,
where L-value is the address of the variable and Rvalue is its content.
Eg:
int *p;
int *ptr1;
float *ptr2;
struct student *ptr3;
The address of a variable can be assigned to pointer variable using address
operator (&)
Eg:
int *p;
int a;
p=&a
* - value at
ptr1 = #
*
fr
-
address of
O
/
ptr1 1001
1500
A ↑
..
↑
25
&
num &
num
1001
&
look
-
-
-
cout<< # 1001
- -
cout<< ptr1; 1001
-
-
cout<< num; 25
-
-
cout<< *ptr1;
- 25 O ptr1 1001
1500
-
cout<< &ptr1; 1500
-
Expor 25
-
-
cout<< *num; num
-
1001
cout<< # // 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;
Int x,*p1,**p2;
X=100;
P1=&x;
P2=&p1
COUT<<**p2;
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.
-
E
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). -
-
Int Xp
Y
p = new
inty
hat int
$
- 2 bits
-
short * si_ptr;
float * fl_ptr;
struct complex * cx_ptr;
si_ptr = new short;
fl_ptr = new float;
cx_ptr = new complex;
-
--si_ptr fl_ptr cx_ptr
-
1001 1010 1200
P
real imagenary
1000 1001 1010 1011 1012 1013 1200 1201 1202 1203
-
Allocated memory locations can also be initialised using the following syntax:
delete pointer_variable;
-
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.
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.
-
STRUCTURES
& POINTERS
Part 3
Contents
Operations on pointers
Arithmetic operations
on pointers
Relational operations
on pointers
Pointer and array
Dynamic array
Pointer and string
Array of strings
Pointer and structure
Self referential structure
Questions
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
real imagenary
1000 1001 1010 1011 1012 1013 1200 1201 1202 1203
cout << si_ptr + 1;
cout << fl_ptr + 1;
What will be the output? Do you think that it will be 1001 and 1011?
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=?
si_ptr+5 = (1000+5×2)=1010
fl_ptr+3 = (1010+3×4)=1022
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.
p==q or p!=q
Pointer and array
Figure 1.9 shows the memory allocation of an array ar[10] of int
type with 10 numbers.
ar -
-
X
34 E]
·
1000
W
12
-
1004
1008 8
&CO]
-
1012 18 Ptr =
1016 24
1020 38
1024 43
1028
1032
14
7 i
1036
O19
7
Write C++ statement to display all the 10 elements of this array.
If ptr is an integer pointer
#
⑭t Apar
;
ptr = &ar[0];
UT -
Ptr = 1000
Int-buty
-
-
~
100 07 1*
" 000 +
E
cout<<ptr; //Displays 1000, the address of ar[0]
- -
-
1004
-
- -
cout<<*ptr; //Displays 34, the value of ar[0] -
- -
+ 9 *3
1000
1000 +36
= ⑯
-
-
Can you predict the output of the statement:
cout<<ar;
output will be 1000
Because array-name always contains the base address of the array, and it
cannot be changed.
Dynamic array
Dynamic array is created during run time using the dynamic memory
allocation operator new.
E
Since there is no size specification, a string of any number of characters
can be stored. There is no wastage or insufficiency of memory space. But it
should be done with initialization. (e.g., char *str = "Program";)
Assignment operator (=) can be used to copy strings.
Any character in the string can be referenced using the concept of
pointer arithmetic which makes access faster.
Array of strings can be managed with optimal use of memory space.
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“)
char *name[7];
This array can contain a maximum of 7 strings, where each string can
contain any number of characters.
struct employee
{
int ecode;
char ename[15];
float salary;
};
employee *eptr;
It is clear that eptr is a pointer that can hold the address of employee
type data. The statement:
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
Self referential structure
--
Self referential structure is a structure in which one of the elements is a
pointer to the same structure.
-
⑳
struct node
{
int date1;
char date2;
struct node *link;
};
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
Q. Run time allocation of memory is triggered by the operator ……
Ans. new.
Q. Define a structure named ‘Time’ with elements hour, minute and second
a) cout<<*(p+2);
b) cout<<*p+3;
Ans.
a)20
b)13
Q. What are the different memory allocations in C++? Explain
Ans. Different memory allocations are: Static and Dynamic Memory Allocation
Arrays Arrays
i) Takes place before the execution of the
program.
struct -
-
{
int regno ;
char name[20] ;
float mark=100 ;
-
};
Ans.
.
.1.struct tagname
2.float mark=100;
Q.Structure with in a structure is termed as -----------------.
Ans.
Nested structure
Q. Consider the given structure definition
{
int real;
int imag;
};
(b) c1.real=15;
⑰
Q. Write the use of * and & operators used in pointer
Ar
Ans.
The dereference operator (*) retrieves the value pointed to by the pointer
Address of operator ( & ), to get the address of a variable
1000 + 2x4
1000
*
* D =
1008 1008
in -
3 - -
cour(P+2
-
Q. Distinguish between array and structure
Ans:
Arrays Arrays
Derived data type User defined data type
Athul
↑HE
Sasa
HAD 1Y a
Seeelekshri
Sinfe
I
Screeekshire
Bezam Abshek
Rahan
Aseam, Gautram Valsak
Dynamic
-
M
-
boya
Ans.
( b) int * ptr = new int [10 ] ; This is creation of a dynamic array of size 10.
Q. What is a pointer in C++ ? Declare a pointer and initialize with the name
of your country.
Ans.
Pointer is a variable that can hold the address of a memory location.
It is a primitive since it contains memory address which is atomic in nature.