• ### UNIT 6: POINTERS AND STRUCTURE IN C++

INTRODUCTORY ACTIVITY

The Groupe Scolaire Nderonziza which is located in District Gakenke, Sector Amahoro,
Cell Bwiza and Village Rumuri is a twelve-year basic education school. It has 4 blocks
of 3 equal classrooms each. Each classroom has 10 meters of length and can contain a
maximum of 30 students. Each classroom is labelled with a name made of the name of
block and the name of the level as showed in the next figure.

After analyzing this figure, respond to the following questions.

1. Describe the role of each label of a classroom?

2. Discuss the way of knowing the content of each classroom?

3. If you are asked to describe the entity student, what are its attributes?

4. In C++ Programming language, how are you going to declare the variable
student?

5. Suppose that at the beginning of the next year there are 60 new students
who are enrolled at that school in S4. If the schools need to maintain the
quality of teaching and learning by keeping a maximum of 30 students
per classroom, what will happen for the 30 students who don’t have
space in S4?

6. In C++ programming language, how to create that space?

6.1 Pointers in C++

ACTIVITY 6.1

1. The student called Kayiranga of Computer Science Senior 5 has a class
work and wants to borrow a C++ programming language book and a
computer from his classmate Iradukunda. Kayiranga needs to use those
materials which are on the desk of Iradukunda to submit the work on
Discuss

a. What could Kayiranga do if he takes those materials without informing

b. What could happen to Iradukunda when he comes back?

3. On The list, the students of Senior 5 are arranged in ascending order
according to their names. From one name of a student, how to reach the
next student?

a. How to get to the student number 5 while you are on student number 2?

b. How to get to the student number 8 while you are on student number 15?

6.1.1 Definition of Pointers

A pointer is a variable which contains the address in memory of another variable.
There can be a pointer to any variable type. The unary or monadic operator & gives
the address of a variable’’. The indirection or dereference operator * gives the
contents of an object pointed to by a pointer’’.

C++ gives the power to manipulate the data in the computer’s memory directly. The
space in the memory can be assigned and de-assigned. This is done using pointer
variables. Pointer variables are variables that points to a specific address in the
memory pointed to by another variable.

6.1.2 Dereference operators

The asterisk sign (*) in the cout statements is called the dereference operator. If the
dereference operator is used, the “value pointed by” a pointer is got.

The statement:

cout << *ptr; means to print the content of the memory space pointed by ptr.

6.1.3 Reference operator

The ampersand sign (&) is called the reference operator. If the reference operator
is used, it will get the “address of” a variable. The ptr = &x; means that it stores the
address of the variable x in the pointer ptr.

6.1.4 Declaring pointer variables

A pointer is declared by using the * (asterisk) operator before an identifier. It is
necessary to initialize the pointer before you can use a pointer in for instance a cout
statement. Due to the ability of a pointer to directly refer to the value that it points
to, it becomes necessary to specify in its declaration which data type a pointer is
going to point to. It is not the same thing to point to a char as to point to an int or a
float.

Pointer declaration Syntax:

data_type *pt_name;

Where data_type is the data type of the value that the pointer is intended to point to.

The following are three declarations of pointers and all of them are pointers and will
occupy the same amount of space in memory:

6.1.5 Initialization of Pointer Variable

Pointers can be initialized to point to specific locations at the very moment they are
defined,You need to initialize a pointer by assigning it a valid address.

6.1.6 Graphical representation of pointers for referencing memory allocation.

Consider the following,

int jim,tom,*blaise;
jim = 10;
tom= jim;
blaise = &jim;

The following is graphical representation of the value contained in each variable
after the execution of this, are shown in the following diagram:

First, we have assigned the value 10 to jim (a variable
whose address in memory we have assumed to be 501).
The second statement copied to tom the content of variable jim which is 10. the
third statement copies to blaise not the value contained in jim but a reference to it (its
address, which we have assumed to be 501). The reason is that in this third assignment
operation we have preceded the identifier jim with the reference operator (&), so
we were no longer referring to the value of jim but to its reference (its address in
memory).

1.1.7 Incrementing a Pointer

Incrementing a pointer is generally used in array because we have contiguous
memory in array and we know the contents of next memory location. Incrementing
pointer variable depends upon data type of the Pointer variable
Three Rules should be used to increment pointer.

The following program increments the variable pointer to access each succeeding
element of the array –

#include <iostream>

6.1.8 Decrementing a Pointer

As shown in example below, the program decrementing a pointer, which decreases
its value by the number of bytes of its data type

#include <iostream>
using namespace std;
const int MAX = 3;

int main () {
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have address of the last element in pointer.
ptr = &var[MAX-1];
for (int i = MAX; i > 0; i--) {
cout << “Address of var[“ << i << “] = “;
cout << ptr << endl;
cout << “Value of var[“ << i << “] = “;
cout << *ptr << endl;
// point to the previous location
ptr--;
}
getchar();
return 0;
}

6.1.9 Arrays and pointers

The name of an array is a pointer to the first element in the array.

int a[10];

int *aptr = a;

a // is equivalent to &a[0]

aptr = a // is equivalent to aptr = &a[0];

aptr+5 // is equivalent to &a[5]

*(aptr+5)

// is equivalent to a[5]

Exemple :
#include <iostream>

using namespace std;

int main()
{
float arr[10];

float *ptr;

cout << “Displaying address using arrays: “ << endl;

for (int i = 0; i < 10; ++i)
{
cout << “&arr[“ << i << “] = “ << &arr[i] << endl;
}
// ptr = &arr[0]

ptr = arr;

cout<<”\n Displaying address using pointers: “<< endl;

for (int i = 0; i < 10; ++i)

{ cout << “ptr + “ << i << “ = “<< ptr + i << endl;
}
getchar();

return 0;}

Different pointer ptr is used for displaying the address of array elements arr. Pointers
are the variables that hold address. Not only can pointers store address of a single
variable, it can also store address of cells of an array.

6.1.10 Comparison of pointers

Pointers may be compared by using relational operators, such as ==, <, and >.

The following program incrementing the variable pointer so long as the address to
which it points is either less than or equal to the address of the last element of the
array, which is &var[MAX - 1].

6.1.11 Subtracting pointers

Differencing means subtracting two Pointers. Subtraction gives the Total number of
objects between them. Subtraction indicates “How apart the two Pointers are?”

Example:

#include<iostream>

using namespace std;

int main()

{
int num , *ptr1 ,*ptr2 ;

ptr1 = &num ;

ptr2 = ptr1 + 2 ;

cout << “ the difference of two pointers is: “ << ptr2 - ptr1 << endl;

getchar ();

return 0;

}

6.1.12 Assignment of pointers

In pointer assignment, the pointer is associated with a target. If the target is undefined
or disassociated, the pointer acquires the same status as the target

pointer-object => target ,

6.1.13 Pointers and function in C++

A function pointer is a variable that stores the address of a function that can later be
called through that function pointer.

Example:

#include<iostream>

using namespace std;

void swapping (int *ptr_a, int *ptr_b)

Activity1:

a. What is the pointer in C++

b. Explain the use of Address Operator (&) and operator (*).

Activity 2:

Given the following declarations, which of the following statements are not valid?

int i;

int *pi;

double d;

double *pd;

a. i=&pi; b.*pi=&i; c. pd=&pi; d. pd=i; e. pi=&i;

Activity3:

What is the error in each of the following expressions?

6.2. Memory allocation

ACTIVITY 6.2

Public bonded warehouse known as MAGERWA (Magazin Generaux Rwandais) is a
Rwandan company where all goods from abroad are stored before being distributed in
the country. When an importer brings his/her goods to MAGERWA, he/she is allocated
a space where to put those goods for checking and is charged the space per square
meter (m2) per day. When he/she withdraws his/her goods from MAGERWA, the
occupied space is given to other customers for use.

Discuss: What would happen to the MAGERWA store if all customers failed to withdraw
their goods on time?

6.2.1 Definition

Memory allocation means reserving memory for specific purposes. It is a process
by which computer programs and services are assigned with physical or virtual
memory space, the process of reserving a partial or complete portion of computer
memory for the execution of programs and processes. Once the program has
finished its operation, the memory is released and allocated to another program
or merged within the primary memory. Programs and services are assigned with a
specific memory as per their requirements when they are executed

6.2.2 Dynamic memory allocation in C++

Up to this level, all memories needed in programs were determined before the
program execution by defining the variables where it is reserved for. But there may
be cases where the memory needed in a program can only be determined during
runtime.

When a memory is dynamically allocated, the operating system is asked to reserve
some of that memory for that program’s use. If it can fulfill this request, it will return
the address of that memory to the current application. From that point forward, the
application can use this memory as it wishes. When the application is done with
the memory, it can return the memory back to the operating system to be given to
another program. This allows to obtain more memory when required and release it
when not necessary.

C++ integrates the operators new and delete for allocating dynamic memory. With
the functions malloc, calloc, realloc and free are available in C++ and can also be
used to allocate and deallocate dynamic memory.

A. Operators:

i. Operator new and new[]

Dynamic memory is allocated using operator new. New is followed by a data type
specifier and, if a sequence of more than one element is required, the number of
these are within brackets []. It returns a pointer to the beginning of the new block of
memory allocated.

Its syntax is:
pointer = new type
pointer = new type [number_of_elements]

The first expression is used to allocate memory to contain one single element of
type type. The second one is used to allocate a block (an array) of elements of type
type, where number_of_elements is an integer value representing the amount of
these. For example:

int * mem;
mem= new int[6];

There is a substantial difference between declaring a normal array and allocating
dynamic memory for a block of memory using new. The most important
difference is that the size of a regular array needs to be a constant expression,
and thus its size has to be determined at the moment of designing the program,
before it is run, whereas the dynamic memory allocation performed by new
allows to assign memory during runtime using any variable value as size.
The dynamic memory requested by a program is allocated by the system from the
memory heap (unused memory of the program). However, computer memory is a
limited resource, and it can be exhausted. Therefore, there are no guarantees that
all requests to allocate memory using operator new are going to be granted by the
system.

ii. Operators delete and delete[]

In most cases, memory allocated dynamically is only needed during specific periods
of time within a program; once it is no longer needed, it can be freed so that the
memory becomes available again for other requests of dynamic memory. This is the
purpose of operator delete, whose syntax is:

delete pointer;

delete[] pointer;

The first statement releases the memory of a single element allocated using new,
and the second one releases the memory allocated for arrays of elements using

new and a size in brackets ([]).
The value passed as argument to delete shall be either a pointer to a memory block
previously allocated with new, or a null pointer (in the case of a null pointer, delete
produces no effect).

b. Functions

Malloc (): void* malloc (size_t size);

Allocate memory block. Allocates requested size of bytes of memory and returns
a pointer to the beginning of the block (first byte of allocated space). Simply pass
in how big you want your memory to be (in bytes), and you get a pointer to that
memory back. The content of the newly allocated block of memory is not initialized,
remaining with indeterminate values. If it fails it returns NULL. It is routine used to
allocate a single block of memory.

Calloc (): void* calloc (size_t num, size_t size);

Allocate and zero-initialize array. Allocates space for an array element, initializes to
zero and then returns a pointer to memory. The calloc() takes two integer arguments
and multiplied together to specify how much memory to allocate. This is routine
used to allocate arrays of memory.

Free (): void free (void* ptr);

Deallocate memory block (the previously allocated space). A block of memory
previously allocated by a call to malloc, calloc or realloc is deallocated, making it
available again for further allocations.

Realloc (): void* realloc (void* ptr, size_t size);

Reallocate memory block, Change the size of previously allocated space pointed to
by ptr. The function may move the memory block to a new location (whose address
is returned by the function).

Notice: In the above program:

Malloc () function dynamically allocates initial value of the size maximum 10
characters (e.g the size of HelloWord has 9 characters) otherwise it returns null and
is copied to str variable which has address in memory.

Realloc() function :reallocate the content of str concatenating with .com and change
the size from 10 to 15 but it keeps the existing address which is 0x22ff44.

Free(): the memory size of (10) characters that has been reallocated with realloc () is
released after using free() because it is no longer needed.

6.2.3 Static memory (or Compile Time) allocation

The memory for your variables is allocated when the program starts, the size is fixed
when the program is created

Statically allocated variables have their storage allocated and initialized before main
starts running and are not deallocated until main has terminated. Statically allocated

local variables are not re-initialized on every call to the function in which they are
declared. A statically allocated variable thus has the occasionally useful property of
maintaining its value even when none of the functions that access the variable are
active.

6.2.4 Advantages of dynamic memory allocation over static memory allocation

An advantage is that the program determines how much memory it needs at run time
and allocate exactly the right amount of storage and released when it’s no longer needed.

• Dynamic Memory Allocation

* Memory allocated “on the fly” during run time

* Dynamically allocated space usually placed in a program segment known
as the heap or the free store

* Exact amount of space or number of items does not have to be known by

* For dynamic memory allocation, pointers are crucial

• Static (or Compile Time) Allocation

* Memory for named variables is allocated by the compiler

* Exact size and type of storage must be known at compile time

* For standard array declarations, this is why the size has to be constant

Application activity 6.2

Activity 1:

Explain the memory allocation and compare dynamic memory over static memory
allocation.

6.3 C++ Structures

ACTIVITY 6.3

The company Urukundo Ltd specialized in production of Milk Powder has a group
of 20 employees and its management is not computerized. Each employee is
identified by the attributes first name, second name, age, degree and salary. The
programmer of that company wants to write a program in C++ programming
language that will allow to constitute a file containing the information of each
employee.

1. What should be the data type of each attribute?

2. Is it easy to enter the value of each attribute one by one? What should
be the solution?

3. If employee is considered as a single entity, how will it be declared in
the program?

6.3.1 Introduction to C++ structure

Structure is a collection of variables of different data types under a single name.
These data elements, known as members, can have different types. To store some
information about a student: Name, Age and student ID. Creation of different
variables name, Age, ID needed to store this information separately.

6.3.2 How to declare a structure in C++ programming?

The struct keyword defines a structure type followed by an identifier (name of the
structure).

Data structures can be declared in C++ using the following syntax:

struct type_name {

member_type1 member_name1;

member_type2 member_name2;

member_type3 member_name3;

. } object_names;

Where:

type_name is a name for the structure type, object_name can be a set of valid
identifiers for objects that have the type of this structure. Within braces {}, there is a
list with the data members, each one is specified with a type and a valid identifier as
its name.

6.3.3 Initializing structure in C++ programming

Just like any variable, we can specify the initial value of a structure at the time of its
definition.

Example of Initialization of structure:

6.3.4 Calculate Memory consumption by structure

To generate the program below, padding must be added to the structs to satisfy this
alignment criteria. It creates two structs; both contain 3 values of the same types
and of the same name. It then prints out the sizes of these structs (in bytes).

Note: Output may vary depending on the systems

The C++ standard defines that struct members must be arranged in memory in the
same order that they are defined within their access level. Different types must have
certain memory alignment requirements; long (on a 64-bit platform) uses 8 bytes of
memory and must start at a memory location divisible by 8 char, on the other hand,
only uses 1 byte of memory and can start at any memory address.

6.3.5 Accessing members of a structure

We need to specify both the structure name (name of the variable) and the member
name when accessing information stored in a structure. There are two types of
operators used for accessing members of a structure:

1. Member operator (.) or Dot Operator

structure_variable_name.member_name

For Example:
We can access the member age of employee structure variable employee_one as:
struct employee
{
char name[50];

int age;

float salary;

char department[30];

} employee_one = {“paul”, 25, 150000.5, “ICT”};

int age = employee_one.age;

2. Structure pointer operator (->) or Arrow Operator (->)

Structure pointer operator or Arrow operator is used to access members of structure
using pointer variable. When we have pointer to a structure variable, then we can
access member variable by using pointer variable followed by an arrow operator
and then the name of the member variable.

structure_pointer->member_name;

For example:

6.3.6 Global use of structure

As defined, a structure is a compound data type that contains different members
of different types, structs are simpler to be managed by the programmer and the
compiler,a better example of using a global variable, and a situation where global
variables are completely necessary, is when passing a structure to a function. In
that case, you must declare the structure as global so that all functions can access
variables of that structure type.

6.3.7 Pointer to structure

Just like other variables we can use pointers to access information stored in a
structure. Structures can also be pointed by pointers and store pointers. The rules
are the same as for any fundamental data type. The pointer must be declared as a
pointer to the structure.

6.3.8 Nesting structure

Structures can be nested within other structures in C++ programming. Structures
can also be nested so that a valid element of a structure can also be another structure.
When a structure contains another structure, it is called nested structure. For
example, we have two structures named Address and Student. To make Address
nested to Student, we have to define Address structure before and outside Student
structure and create an object of Address structure inside Student structure.

Syntax for structure within structure or nested structure

struct structure1
{
- - - - - - - - - -
- - - - - - - - - -
};
struct structure2
{
- - - - - - - - - -
- - - - - - - - - -
struct structure1 obj;
};

Example:

6.3.9 Array of structure

Arrays of structure are good for storing information of a single entity. By declaring
an array of structures, you specify the number of reserved structures inside array
brackets when you declare the structure variable.

Example:

Consider learning activity 6.3 example:

#include <iostream>

#include <conio.h>

#include<stdio.h>

#include<string.h>

using namespace std;

struct Employee

Application activity 6.3

1.
a. Define a structure in C++
b. Given a structure definition,
struct Employee {
string emName;
string emSex;
}; Employee Emp;
A member of the structure can be accessed by which one of the following statements?:

a. Employee.emName;

b. Emp.emName;

c. Emp->emName;

2. Store Information of students and Display It Using Structure by creating an
array having 4 elements of structure student. Each of the element stores the
information of a student.

For example, st[0] stores the information of the first student, st[1] for the
second and so on.

3. What is the output of the following program?

END UNIT ASSESSMENT

UNIT 5: DATABASE DESIGNUNIT 7: OBJECT ORIENTED PROGRAMMING IN C++