You are on page 1of 27

Kombolcha Institute of Technology

College of Informatics
Department Computing and Engineering
Fundamental Programming 2

KIOT@SEMarch 2017 Workie


by Ashenafi
Chapter One

Pointer

Department Information System

Prepared by. Ashenafi Workie

KIOT@SE by Ashenafi Workie


Basic concept of pointers
 The memory of your computer can be imagined as a
succession of memory cells, each one of the minimal size
that computers manage (one byte). These single-byte
memory cells are numbered in a consecutive way, so as,
within any block of memory, every cell has the same
number as the previous one plus one.
 This way, each cell can be easily located in the memory
because it has a unique address and all the memory cells
follow a successive pattern. For example, if we are looking
for cell 1776 we know that it is going to be right between
cells 1775 and 1777, exactly one thousand cells after 776
and exactly one thousand cells before cell 2776.

KIOT@SE by Ashenafi Workie 3


Reference operator (&)

 As soon as we declare a variable, the amount of memory


needed is assigned for it at a specific location in memory (its
memory address). We generally do not actively decide the
exact location of the variable within the panel of cells. It is a
task automatically performed by the operating system during
runtime. However, in some cases we may be interested in
knowing the address where our variable is being stored
during runtime in order to operate with relative positions to it.

The address that locates a variable within memory is a


reference to that variable. This reference to a variable can be
obtained by preceding the identifier of a variable with an
ampersand sign (&), known as reference operator, and which
can be literally translated as "address of". For example:
KIOT@SE by Ashenafi Workie 4
Look at this example

ptr = &Var;
//Ptr now holds the address of the variable ’var’.
E.g. // demo of the reference operator
//this prog prints the addresses of the three variables.

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int var1=10,var2=20,var3=30;
cout<<endl<<&var1<<endl<<&var2<<endl<<&var3;
return 0;
}

KIOT@SE by Ashenafi Workie 5


Get in to detail

 The variable that stores the reference to another


variable is called a pointer. In other words,
pointers are variables that hold an address value.
Pointers are very powerful features (but
hobgoblin) of the C++ language that have many
uses in advanced programming. Besides offering
a very efficient method of accessing data, they
provide efficient technique for manipulating data
in arrays, they are used in functions for reference
parameters, and they are the basis for dynamic
allocation of memory.
KIOT@SE by Ashenafi Workie 6
Dereference operator (*)

Pointers are said to "point to" the variable whose reference they
store. Using a pointer we can access the value stored in the
variable which it points to. To do this, we simply have to precede
the pointer's identifier with an asterisk (*), which acts as
dereference operator and that can be literally translated to "value
pointed by". Therefore, following with the values of the previous
example, if we write:
// Value = *Ptr;
read as: "Value equals to value pointed by Ptr"
N.B Ptr refers to the address location( say 1776), while *Ptr (with
an asterisk * preceding the identifier) refers to the value stored at
address 1776. Notice the difference of including or not including
the dereference operator
KIOT@SE by Ashenafi Workie 7
Let see with example

 // Value = *Ptr;
 Ptr2 = Ptr; // Ptr2 equal to Ptr ( 1776 )
 Ptr2 = *ptr; // Ptr2 equal to value pointed by ted (say 736 )

& is the reference operator and can be read as "address of"


* is the dereference operator and can be read as "value
pointed by"
 Thus, they have complementary (or opposite) meanings. A
variable referenced with & can be dereferenced with *.

KIOT@SE by Ashenafi Workie 8


Declaring Pointer Variables

 Pointers are declared similar to normal variables,


but you must specify when you declare them what
they are going to point to. If you declare a pointer to
point to an integer, then it can't be used to point to a
floating point value etc. The pointer is declared
using the * symbol which is put between the name
of the variable and the type that it is to point to. For
instance, to declare a pointer called my_Ptr which is
to point to an integer, you would do it using either of
these: int* my_ptr;
 Int *my_ptr;

KIOT@SE by Ashenafi Workie 9


Cont.…d
 Here's something you should be careful of! If you
declare several variables on one line and put float*
or something similar in front of them, only variables
with a * directly in front of them will be pointers.
Here's an example:
 double* first, second, third; // 'first' is a pointer
'second' and 'third' are ordinary variables.
 double* a,*b,*c; // All these variables are pointers to double
values.
 long *x, y, *z; // 'x' and 'z' are pointers, but 'y' is an
ordinary long variable.

KIOT@SE by Ashenafi Workie 10


Example 1
#include<iostream>
#include<conio.h>
using namespace std;
int main(){
float *p;
float a = 12.13;
float b = 0.0045;
p = &a;
cout << p << endl; // The address of a
cout << *p << endl; // The value of a
*p *= 4; // Multiply 'a' by 4
p = &b;
cout << p << endl; // The address of b
cout << *p << endl; // The value of b
*p += 10; // Add 10 to 'b'
cout << a << endl; // Display new value of 'a'
cout << b << endl; // Display new value of 'b'
return 0;}
KIOT@SE by Ashenafi Workie 11
Example 2
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int firstvalue = 5, secondvalue = 15;
int * ptr1, * ptr2; //declaration
ptr1 = &firstvalue; // p1 = address of firstvalue
ptr2 = &secondvalue; // p2 = address of secondvalue
*ptr1 = 10; // value pointed by p1 = 10
*ptr2 = *ptr1; // value pointed by p2 = value pointed by p1
ptr1 = ptr2; // p1 = p2 (value of pointer is copied)
*ptr1 = 20; // value pointed by p1 = 20
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0; }

KIOT@SE by Ashenafi Workie 12


Pointers and arrays

 The concept of array is very much bound to that


of pointer. The identifier of an array is equivalent
to the address of its first element, as a pointer is
equivalent to the address of the first element that
it points to, so in fact they are the same concept.
 Consider these two declarations:

int numbers [5];


int* ptr;
The following assignment operation would be
valid:
p = numbers;
KIOT@SE by Ashenafi Workie 13
Cont.…..ed

 After that, p and numbers would be equivalent


and would have the same properties. The only
difference is that we could change the value of
pointer p by another one, whereas numbers will
always point to the first of the 5 elements of type
int with which it was defined. Therefore, unlike p,
which is an ordinary pointer, numbers is an array,
and an array can be considered a constant
pointer. Therefore, the following allocation would
not be valid:
 numbers = p;//// we cannot assign values to
constants.
KIOT@SE by Ashenafi Workie 14
Array with pointer

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int numbers[]={10,20,30,40,50};
for (int j = 0 ; j<5; j++)
cout<<* (numbers +j)<< endl; // displays the
contents one by one
return 0;
}

KIOT@SE by Ashenafi Workie 15


Description

 Note: we cannot say numbers++ since numbers


is an address constant and it is not possible the
change a constant by using the increment
operator. But, we can assign the address
constant to a pointer variable, and the
 n it is possible to use the increment operator on
the pointer variable.

KIOT@SE by Ashenafi Workie 16


Pointer arithmetic
 In C++ one can add an integer quantity to or subtract an
integer quantity from a pointer. This is frequently used by
programmers and is called pointer arithmetic. Pointer
arithmetic is not the same as integer arithmetic, because the
outcome depends on the size of the object pointed to. For
example, suppose that an int is represented by 4 bytes.
Now, given
 char *str = "HELLO";
 int nums[] = {10, 20, 30, 40};
 int *ptr = &nums[0]; // pointer to first element
 str++ advances str by one char (i.e., one byte) so that it
points to the second character of "HELLO", whereas ptr++
advances ptr by one int (i.e., four bytes)so that it points to
the second element of nums. This is shown below:
KIOT@SE by Ashenafi Workie 17
Pointer arithmetic

It follows, therefore, that the elements of "HELLO" can be referred to as *str,


*(str + 1), *(str + 2), etc. Similarly, the elements of nums can be referred to as
*ptr, *(ptr + 1), *(ptr + 2), and *(ptr + 3).
Another form of pointer arithmetic allowed in C++ involves subtracting two
pointers of the same type.
For example:

KIOT@SE by Ashenafi Workie 18


int *ptr1 = &nums[1];
int *ptr2 = &nums[3];
int n = ptr2 - ptr1; // n becomes 2
void pointers/Pointers to void/
 The void pointer is a special type of pointer that points to a
value that has no type (and thus also an undetermined length).
This allows void pointers to point to any data type, from an
integer value or a float to a string of characters.
 But in exchange they have a great limitation: the data pointed
by them cannot be directly dereferenced [b/c there is no type to
dereference to] and for that reason we will always have to
change the type of the void pointer [Cast] to some other pointer
type that points to a concrete data type before dereferencing it.

KIOT@SE by Ashenafi Workie 19


#include<iostream>
#include<conio.h>
using namespace std;
void increase (void* data, int size) //function defintion
{
switch (size) {
case sizeof(char) : (*((char*)data))++; break;
case sizeof(int) : (*((int*)data))++; break;
}}
int main (){
char a = 'x';
int b = 1602;
increase (&a,sizeof(a));
increase (&b,sizeof(b));
cout << a << ", " << b << endl;
return 0;}

KIOT@SE by Ashenafi Workie 20


Pointers and strings
 Since strings are arrays of type char, pointer notations on arrays can
be applied to the characters in strings. E.g.
#include<iostream>
#include<conio.h>
using namespace std;
int main(){
char str1[]="This string is defined as an array ";
char* str2="This string is defined as a pointer";
cout <<str1 << endl; // displays str1
cout << str2<< endl; // displays str2
str1 ++ ; // can't do this, str1 is constant
str2++; // this is OK, str2 is a pointer variable
cout<<str2; // displays “his string is defined a pointer” b/c
it was incremented by 1 byte.
return 0;
}

KIOT@SE by Ashenafi Workie 21


Pointers and functions
 We can use pointers to pass value from calling program to a function. Like passing
values by reference, passing values to functions by pointers is also used when the
function is intended to modify variables in the calling program.
#include<iostream>
#include<conio.h>
using namespace std;
void To_Celsius (float *);
int main(){
float Fahr;
cout <<"Enter temperature in Fahrenheit: ";
cin>>Fahr;
To_Celsius(&Fahr);
//calling the To_Celsius function by passing address of Fahr
cout<<"In Celsius, it is: " << Fahr;
return 0;}
void To_Celsius(float *PtrToFahr) //definition of the
To_Celsius function
{ *PtrToFahr=(*PtrToFahr-32)*5/9;
}
KIOT@SE by Ashenafi Workie 22
Dynamic Memory
 Until now, in all our programs, we have only had as
much memory available as we declared for our
variables, having the size of all of them to be
determined in the source code, before the
execution of the program. But, what if we need a
variable amount of memory that can only be
determined during runtime? For example, in case
that we need some user input to determine the
necessary amount of memory space. The answer
is dynamic memory, for which C++ integrates the
operators new and delete.

KIOT@SE by Ashenafi Workie 23


Operators new and new[]

In order to request dynamic memory we use the 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 within brackets []. It returns
a pointer to thebeginning of the new block of memory allocated.
Its form is: pointer = new type //where pointer is a pointer variable
pointer = new type [number_of_elements]
he first expression is used to allocate memory to contain one single
element of type type. The second one is used to assign a block (an
array) of elements of type type,wh ere number_of_elements is an
integer value representing the amount of these.
For example: // the system dynamically assigns
space
for five elements of type int and //returns a pointer to the first element
of the sequence, which is //assigned to Ptr.
KIOT@SE by Ashenafi Workie 24
Operators delete and delete[]

 The dynamic memory requested by our program is


allocated by the system from the memory heap. However,
computer memory is a limited resource, and it can be
exhausted. Therefore, once it is no longer needed, it should
be freed so that the memory becomes available again for
other requests of dynamic memory. This is the purpose of
the operator delete, whose format is:
delete pointer;
delete [] pointer;

KIOT@SE by Ashenafi Workie 25


 #include<iostream>  for (i=0; i<n; i++)
 #include<conio.h>  {
 using namespace std;  cout << "Enter a number: ";
 int main()  cin >> p[i];
 {  }
 int i, n;  cout << "You have entered: ";
 int* p; //p is a pointer variable  for (i=0; i<n; i++)
 cout << "How many numbers would  cout << p[i] << ", "; //comma
you like to Enter? "; separated output
 cin >>n;  delete[] p; //free the
 p= new int[n]; // n amount of
allocated memory
blocks allocated dynamically }

 if (p == NULL) //or return 0;
if(p==0)
} 
 cout << "Error: memory could not
be allocated";
 else //if allocation was
successful
 { KIOT@SE by Ashenafi Workie 26
Any ambiguous

Questions

KIOT@SE by Ashenafi Workie 27

You might also like