You are on page 1of 29

In the Name of Allah the Most

Beneficent the Most Merciful

Subject : Data Structures & Algorithms

Lecture : 02

Monday, January 18, 2021 1


Arrays
 An array is a data structure which allows a collective name to be
given to a group of elements which all have the same type. An
individual element of an array is identified by its own
unique index (or subscript).

 An array is a collective name given to a group of similar quantities.


These similar quantities could be percentage marks of 100 students,
number of chairs in home, or salaries of 300 employees or ages of 25
students.

 Thus an array is a collection of similar elements. These similar


elements could be all integers or all floats or all characters etc.
Usually, the array of characters is called a “string”, where as an array
of integers or floats is called simply an array. 
Monday, January 18, 2021 2
Arrays
 You have already studied about arrays and are well-
versed with the techniques to utilize these data structures.
Here we will discuss how arrays can be used to solve
computer problems. Consider the following program:

 main()
 {
 int x[6];
 int j;
 for(j = 0; j < 6; j++)
 x[j] = 2 * j; //We have declared an int array of six
elements and initialized it in the loop.
 }
Monday, January 18, 2021 3
Arrays
Let’s revise some of the array concepts:
Array declaration: int x[6]; or float x[6]; or double x[6];
An array is collection of cells of the same type.

The collection has the name ‘x’.


The cells are numbered with consecutive integers.
We can only store integers in this array. We cannot put int in first
location, float in second location and double in third location.
Its individual items are numbered from zero to one less than array size.
To access a cell, use the array name and an index:
x[0], x[1], x[2], x[3], x[4], x[5]
Array Layout

The arrays look like in the memory


x[0]
as follows:
Array cells are x[1]
contiguous in
x[2]
computer memory
x[3]
The memory can be
thought of as an x[4]
array
x[5]

In case of the above example, if some location is assigned to x[0], the


next location can not contain data other than x[1]
What is Array Name?
 ‘x’ is an array name but there is no variable x.
 ‘x’ is not an lvalue.
 If some variable can be written on the left- hand side of an
assignment statement, this is lvalue variable. It means it has some
memory associated with it and some value can be assigned to it.
 For example, if we have the code
Why can’t we do that? Number 2 is a
int a, b; constant. If we allow assignment to
then we can write constants what will happen? Suppose ‘a’ has
b = 2; the value number 3. Now we assigned
a = b; number 2 the number 3 i.e. all the number
2 will become number 3 and the result of 2
a = 5;
+ 2 will become 6. Therefore it is not
allowed.
But we cannot write
2 = a;
Array Name
 ‘x’ is a name of array and ‘x’ is not an lvalue. So it cannot be
used on the left hand side in an assignment statement. Consider
the following statements

int x[6];
int n;
x[0] = 5;
x[1] = 2;
x = 3; // not allowed
x = a + b; // not allowed
x = &n; // not allowed
Array Name…
 What does the statement x = 3; mean? As x is a name of array and
this statement is not clear, what we are trying to do here? Are we
trying to assign 3 to each element of the array? This statement is
not clear. Resultantly, it can not be allowed.

 The statement x = a + b is also not allowed. There is nothing


wrong with a + b. But we cannot assign the sum of values of a and
b to x. In the statement x = &n, we are trying to assign the memory
address of n to x which is not allowed.

 The reason is the name x is not lvalue and we cannot assign any
value to it. For understanding purposes, consider x as a constant. Its
name or memory location can not be changed. This is a collective
name for six locations. We can access these locations as x[0], x[1]
up to x[5].
Monday, January 18, 2021 8
Dynamic Arrays
 You would like to use an array data structure but you do not know
the size of the array at compile time.

 You find out when the program executes that you need an integer
array of size n=20.

 On finding it, the computer will give the address of first location to
the programmer which will be stored in y.

 Allocate an array using the new operator:

int* y = new int[20]; // or int* y = new int[n]


y[0] = 10;
y[1] = 15; // use is the same
Dynamic Arrays
 Here ‘y’ is a lvalue; it is a pointer that holds the address of 20
consecutive cells in memory.

 When we said int* y = new int[20]; the new returns the memory
address of first of the twenty locations and we store that address
into y. As y is a pointer variable so it can be used on the left-hand
side. We can write it as:
y = &x[0];
y = x;
 the statement y = x is also correct. x is an array of six elements that
holds the address of the first element. But we cannot change this
address. However we can get that address and store it in some other
variable. As y is a pointer variable and lvalue so the above
operation is legal
Dynamic Arrays
 We have dynamically allocated the memory for the array. This
memory, after the use, can be released so that other programs
can use it. We can use the delete keyword to release the memory.
The syntax is:
delete[ ] y;

 We are releasing the memory, making it available for use by


other programs.

 We would not do this to the x array because we did not use new
to create it.

 So it is not our responsibility to delete x.


Pointer Data Type and Pointer Variable
 When a variable is declared, the memory needed to store its value
is assigned a specific location in memory (its memory address).
Generally, C++ programs do not actively decide the exact memory
addresses where its variables are stored.

 Fortunately, that task is left to the environment where the program


is run - generally, an operating system that decides the particular
memory locations on runtime.

 However, it may be useful for a program to be able to obtain the


address of a variable during runtime in order to access data cells
that are at a certain position relative to it.

Monday, January 18, 2021 12


Pointer Data Type and Pointer Variable

 The value belonging to pointer data types are the memory


addresses of your computer. However, there is no name
associated with the pointer data type in C++. Because the
domain, (that is the value of a pointer data type), consist of
addresses (memory locations).

 Pointer Variable: A variable whose content is an address


(that is a memory address).

Monday, January 18, 2021 13


Reference operator (&)
 The address of a variable can be obtained by preceding the
name of a variable with an ampersand sign (&), known
as reference operator, and which can be literally translated as
"address of". For example:

 foo = &myvar;

 This would assign the address of variable myvar to foo; by


preceding the name of the variable myvar with the reference
operator (&), we are no longer assigning the content of the
variable itself to foo, but its address.
 
Reference operator (&)
 The actual address of a variable in memory cannot be known before
runtime, but let's assume, in order to help clarify some concepts,
that myvar is placed during runtime in the memory address 1776.

 In this case, consider the following code fragment:

 myvar = 25;
 foo = &myvar;
 bar = myvar;

 The values contained in each variable after the execution of this are
shown in the following diagram:  
Reference operator (&)

 First, we have assigned the value 25 to myvar (a variable whose address in


memory we assumed to be 1776).
 The second statement assigns foo the address of myvar, which we have
assumed to be 1776.
 Finally, the third statement, assigns the value contained in myvar to bar. This
is a standard assignment operation, as already done many times earlier.
 The main difference between the second and third statements is the
appearance of the reference operator (&).
Dereference operator (*)
 The variable that stores the address of another variable (like foo in the
previous example) is what in C++ is called a pointer. Pointers are a
very powerful feature of the language that has many uses in lower
level programming.

 Therefore, following with the values of the previous example, the


following statement:

 baz = *foo;

 This could be read as: "baz equal to value pointed to by foo", and the
statement would actually assign the value25 to baz, since foo is 1776,
and the value pointed to by 1776 (following the example above)
would be 25.
Dereference operator (*)

 It is important to clearly differentiate that foo refers to the


value 1776, while *foo (with an asterisk * preceding the identifier)
refers to the value stored at address 1776, which in this case is 25.
Notice the difference of including or not including the dereference
operator (I have added an explanatory comment of how each of
these two expressions could be.

 baz = foo; // baz equal to foo (1776)


 baz = *foo; // baz equal to value pointed to by foo (25)
Dereference operator (*)

 myvar = 25;
 foo = &myvar;

 Right after these two statements, all of the following


expressions would give true/false as result:

 myvar == 25
 &myvar == 1776
 foo == 1776
 *foo == 25
Declaring Pointer Variables
 The value of a pointer variable is an address. That is the value
refers to another memory space. The data is typically stored in this
memory space. Therefore when you declare a pointer variable, you
also specify the data type of the value to be stored in the memory
location to which the pointer variable points.

 The declaration of pointers follows this syntax:


 type * name; 
 where type is the data type pointed to by the pointer. This type is
not the type of the pointer itself, but the type of the data the pointer
points to. For example:
 int * number;
 char * character;
 double * decimals;
Declaring Pointer Variables

 Note that the asterisk (*) used when declaring a pointer


only means that it is a pointer (it is part of its type
compound specifier), and should not be confused with
the dereference operator seen a bit earlier, but which is
also written with an asterisk (*).

 They are simply two different things represented with the


same sign.
Pointer example 1
 #include <iostream>
 using namespace std;
  int main () { int *p;
 int num1=5, num2=8;
 P = &num1; //stores the address of num1 into p
 cout<< “&num1 = ”<<&num1 << “ P = “<< p<<endl;
 Cout<< “num1 = ” << num1<< “*p =“<< *p<< endl;
 *p = 10;
 Cout<< “num1 = ”<<num1<<“*p = ”<< *p<< endl;
 P = &num2; //stores the address of num2 into p
 Cout<<“&num2 = ”<< &num2<< “p = ”<<p<<endl;
 Cout<<“ num2 = ”<< num2<< “*p = ”<< *p<<endl;
 *p = 2 * (*p);
 cout<<“ num2 = ”<<num2<< “*p = ”<<*p<<endl;
 return 0; }
Pointer example 2
 #include <iostream>
 using namespace std;
 int main ()
 { int firstvalue = 5, secondvalue = 15;
 int * p1, * p2;
   p1 = &firstvalue; // p1 = address of firstvalue
 p2 = &secondvalue; // p2 = address of secondvalue
 *p1 = 10; // value pointed to by p1 = 10
 *p2 = *p1; // value pointed to by p2 = value pointed by p1
 p1 = p2; // p1 = p2 (value of pointer is copied)
 *p1 = 20; // value pointed by p1 = 20
 cout << "firstvalue is " << firstvalue << '\n';
 cout << "secondvalue is " << secondvalue << '\n';
 return 0; }
Pointer Arithmetic
 To conduct arithmetical operations on pointers is a little different
than to conduct them on regular integer types. To begin with, only
addition and subtraction operations are allowed; the others make no
sense in the world of pointers. But both addition and subtraction
have a slightly different behavior with pointers, according to the
size of the data type to which they point.

 When fundamental data types were introduced, we saw that types


have different sizes. For example: char always has a size of 1
byte, short is generally larger than that, and int and long are even
larger; the exact size of these being dependent on the system. For
example, let's imagine that in a given system, char takes 1
byte, short takes 2 bytes, and long takes 4.
Pointer Arithmetic
 Suppose now that we define three pointers in this compiler:
 char *mychar;

 short *myshort;

 long *mylong;

 and that we know that they point to the memory


locations 1000, 2000, and 3000, respectively.
 Therefore, if we write:

 ++mychar;

 ++myshort;

 ++mylong;

mychar, as one would expect, would contain the value 1001. But not so
obviously, myshort would contain the value 2002, and mylong would
contain 3004, even though they have each been incremented only
once.
Pointer Arithmetic

 This is applicable both when adding and subtracting any number to a


pointer. It would happen exactly the same if we wrote: 
 mychar = mychar + 1;
 myshort = myshort + 1;
 mylong = mylong + 1;
Regarding the increment (++) and decrement (--) operators, they both can be used as
either prefix or suffix of an expression, with a slight difference in behavior: as a
prefix, the increment happens before the expression is evaluated, and as a suffix,
the increment happens after the expression is evaluated.
Pointer Arithmetic
 Essentially, these are the four possible combinations of the
dereference operator with both the prefix and suffix versions of the
increment operator (the same being applicable also to the
decrement operator):

 *p++ // same as *(p++): increment pointer, and dereference


unincremented address
 *++p // same as *(++p): increment pointer, and dereference
incremented address
 ++*p // same as ++(*p): dereference pointer, and increment the
value it points to
 (*p)++ // dereference pointer, and post-increment the value it
points to
Pointers and constant
 Pointers can be used to access a variable by its address, and this
access may include modifying the value pointed. But it is also
possible to declare pointers that can access the pointed value to read
it, but not to modify it. For this, it is enough with qualifying the type
pointed by the pointer as const. For example:

 int x;
 int y = 10;
 const int * p = &y;
 x = *p; // ok: reading p
 *p = x; // error: modifying p, which is const-qualified

Here p points to a variable, but points to it in a const-qualified manner,


meaning that it can read the value pointed, but it cannot modify it.
The END

Question and Answer

Monday, January 18, 2021 29

You might also like