CHAPTER 1: STRUCTURES AND POINTERS
Structure
Stricture is a user defined data type.
It is a collection of different data types.
A structure is defined by using the keyword 'struct'.
Elements of a structure are accessed by using .(dot) operator.
Syntax Example
struct structure_tag struct student
{ {
data_type variable1; int roll_no;
data_type variable2; char grade;
...................; float percentage;
...................; };
data_type variableN;
};
Nested Structure
A structure placed inside another structure is called a nested structure.
struct student
int adm_no;
char name [ 20 ];
struct date
short day;
short month;
short year;
dt_adm;
float fee;
};
Array Vs Structure
Array Structure
It is a derived data type. It is a user-defined data type
A collection of same type of data. A collection of different type of data.
Elements are accessed by using subscripts. Elements are accessed by using .(dot) operator.
When an element of an array becomes another array, When an element of a structure becomes another
multi-dimensional array is formed. structure, nested structure is formed.
Pointer
A pointer is a variable which contains a memory address
Syntax Example
Datatype * pointer variable Int *a
Here, 'a' is a pointer variable which contains the address of a memory location used to store integer type of data
The Operators & and *
The address of operator (&), is used to get the address of a variable
* is used to get value stored at the location points by a pointer
Eg:- int val = 5 ;
int *ptr = &val;
ptr val
OxFE 5
Ox83 OxFE
cout<<*ptr : 5
cout<<val : 5
cout<<&val : OxFE
cout<<ptr: OxFE
Memory Allocation
1. Static Memory Allocation:- Memory Allocation before the execution of the program
2. Dynamic Memory Allocation:- Memory Allocation during the execution of the program
new and delete operator
new operator is used for dynamic memory allocation
delete operator is used to remove the memory allocation
Memory Leak
If the memory created by the new operator is not removed by the delete operator, then this memory will be blocked and
will not be re-allocated. Then arises a situation known as Memory Leak
Self referential structure
It is a structure in which one of the elements is a point of the same structure
Eg:
struct employee
int ecode;
char ename[15];
float salary;
employee *ep;
};