0% found this document useful (0 votes)
4 views

Structures & Pointers 2

Uploaded by

sledgo999
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Structures & Pointers 2

Uploaded by

sledgo999
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 105

Chapter 1

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.

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 −

E
struct structure tag
{
data_type variable;
data_type variable;
data_type variable;
……………………………..
……………………………..
data_type variable;

} [one or more structure variables];


Eg:-

{
=
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

Struct structure-name structure-variable;


or
- -

struct structure_tag var1, var2, ..., varN;


or
--
- -
-
-

-
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.

struct student Int-sbuts


{
-

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

4 Bytes 10 Bytes 4 Bytes


Variable initialisation

structure_tag variable={value1, value2,..., valueN};

Eg:

student s={3452, "Vaishakh", "Science", 270.00};


adm_no name group fee
3452 Vaishakh Science 270.00

adm_no name group fee


3452 Vaishakh Science 270.00
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”;
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

struct date struct student


{ {
short day; int adm_no;
short month; char name[20];
-

short year; struct date


}; {
struct student short day;
{ short month;
int adm_no; short year;
char name [20]; } dt_adm;
date dt_adm; float fee;
float fee; };
};
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;
outer_structure_varaiable.inner_structure_variable.element
-
E
Arrays Structures
It is a derived data type. It is a user-defined data type
-
-

A collection of same type of data. A collection of different types of


- data. -

Elements of an array are referenced


using the corresponding subscripts. Elements of structure are -
-
referenced using dot operator (.)
When an element of an array
becomes another array, multi- When an element of a structure
-

dimensional array is formed. becomes another structure, nested


- -

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.

Figure 1.5 shows that L-value of num is 1001 and R-value is 25


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;
The address of a variable can be assigned to pointer variable using address
operator (&)

Eg:

int *p;
int a;
p=&a
* - value at
ptr1 = &num;

*
fr
-
address of

O
/
ptr1 1001
1500
A ↑

..

25
&
num &

num
1001

&
look
-
-
-
cout<< &num; 1001
- -
cout<< ptr1; 1001
-
-

cout<< num; 25
-
-
cout<< *ptr1;
- 25 O ptr1 1001
1500
-
cout<< &ptr1; 1500
-

Expor 25
-
-
cout<< *num; num
-
1001
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
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;
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.
-

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). -
-

following syntax is used for dynamic memory allocation:


pointer_variable = new data_type;
-

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:

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);


-
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.
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
-
Arrays Arrays
i) Takes place before the execution of the
program.

ii) new operator is required

ii) Pointer is essential

iv) Data is referenced using variables

v) No statement is needed for de- allocation


Chapter 1

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

si_ptr fl_ptr cx_ptr

1000 1010 1200

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

This kind of operation is practically wrong.


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 initialisation with 5*/
ptr2 = ptr1 + 1; /* ptr2 will point to the very next
integer location with the address 1004 */
++ptr2; // Same as ptr2 = ptr2 + 1
cout<< ptr1; // Displays 1000
cout<< *ptr1; // Displays 5
cout<< ptr2; // Displays 1004
cin>> *ptr2; /* Reads an integer (say 12) and
stores it in location 1004 */
cout<< *ptr1 + 1; // Displays 6 (5 + 1)
cout<< *(ptr1 + 2);// Displays 12, the value at 1004
ptr1--; // Same as ptr1 = ptr1 - 1
To find the average height of students
#include <iostream>
using namespace std;
int main()
{
int *ht_ptr, n, s=0;
float avg_ht;
ht_ptr = new int; //dynamic memory allocation
cout<<"Enter the number of students: ";
cin>>n;
for (int i=0; i<n; i++)
{
cout<<"Enter the height of student "<<i+1<<" - ";
cin>>* (ht_ptr+i); //to get the address of the next location
s = s* (ht_ptr+i);
}
avg_ht = (float)s/n;
cout<<"Average height of students in the class = "<<avg_ht;
return 0;
Enter the number of students: 5
Enter the height of student 1 - 170
Enter the height of student 2 - 169
Enter the height of student 3 - 175
Enter the height of student 4 - 165
Enter the height of student 5 - 177
Average height of students in the class = 171.199997
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.


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
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] -

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] -

+ 9 *3
1000

1000 +36
= ⑯
-
-
Can you predict the output of the statement:

cout<<ar;
output will be 1000

The address of the first location of the array


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.
Dynamic array
Dynamic array is created during run time using the dynamic memory
allocation operator new.

The syntax is:

pointer = new data_type[size];


To find the highest percent of pass in schools
#include <iostream>
using namespace std;
int main()
{
float *pass, max;
int i, n;
cout<<"Enter the number of schools: ";
cin>>n; //To input number of schools
pass new float [n]; //dynamic array having n elements
for (i=0; i<n; i++)
{
cout<<"Percent of pass by school "<<i+1<<": ";
cin>>pass[i]; //Concept of subscripted variable
}
max=pass[0];
for (i=1; i<n; i++) if (pass[i]>max) max = (pass+i);
/* Elements are accessed using subscript and pointer arithmetic operation */
cout<<"Highest percent is '<<max;
return 0;
}
Pointer and string
String data can be referenced by character array

char str[20]; //character array declaration


char *sp; //character pointer declaration
cin>>str; //To input a string, say "Program"
cout<<str; //Displays the string "Program"
sp=str; //Content of str is copied into the pointer sp
cout<<sp; //Displays the string "Program"
cout<<&str[0]; //Displays the string "Program"
cout<<sp+1; //Displays the string "rogram"
cout<<&str+1; //Displays the string "rogram"
/* The two statements given above display the substring
starting from 2nd character onwards */
cout<<str[0]; //Displays the character 'P'
cout<<*sp; //Displays the character 'P'
cout<<&str; //Displays the base address of the array str
cout<<&sp; //Displays the address of the pointer sp
Advantages of character pointer

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“)

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"}; \
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;
It is clear that eptr is a pointer that can hold the address of employee
type data. The statement:

eptr = new employee;


eptr

ecode ename salary


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
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

Ans. struct Time


{
int hour;
int minute;
int second;
};
Q. Read the following C++ code
int a[5]={10,15,20,25,30};
int *p=a;
Write the output of the following statements:

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.

ii) new operator is required

ii) Pointer is essential

iv) Data is referenced using variables

v) No statement is needed for de- allocation


Q. Identify and correct the errors in the following code fragment

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;
};

a) Write a C++ statement to create a structure variable


b) write a C++ statement to store the value 15 to the structure member real
Ans.

(a) complex c1;


or
struct complex c1;
or
struct complex
{
int real;
int imag;
}c1;

(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

Same type of data Different type of data

Elements are referenced using Elements are referenced using


subscripts .(dot) operator

Multi dimensional array Nested structure

Array of structures Elements as arrays


Ans: -
Q. How will you free the allocated memory?

Using delete operator

Athul
↑HE
Sasa

HAD 1Y a

Seeelekshri
Sinfe

I
Screeekshire
Bezam Abshek
Rahan
Aseam, Gautram Valsak

NeIPcA Adwaith. Rushan


Adviel pacjnl
-
Q. What is the difference between the declaration statements given below ?
-
( a ) int * ptr = new int ( 10 ) ; -

( b ) int * ptr = new int [10 ] ; -


-

Dynamic
-
M
-
boya
Ans.

( a ) int * ptr = new int ( 10 ) ; This is dynamic initialization of a pointer


variable with value 10.

( 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.

char *name_of_nation = “ India “ ;

You might also like