You are on page 1of 34

DILLA UNIVERSITY

COLLEGE OF ENGINEERING AND TECHNOLOGY


SCHOOL OF COMPUTING AND INFORMATICS
DEPARTMENT OF COMPUTER SCIENCE
Fundamental of Programming –II in C++

Chapter -2 Pointer in C++

Prepared by Nega Teferra (M.Tech on CSE)


What is pointer?
 A pointer refers to a variable that holds the address of another
variable.
 Like regular variables, pointers have a data type.
 For example, a pointer of type integer can hold the address of a
variable of type integer.
 A pointer of character type can hold the address of a variable of
character type.
 You should see a pointer as a symbolic representation of a memory
address.
 With pointers, programs can simulate call-by-reference.
 They can also create and manipulate dynamic data structures.
 In C++, a pointer variable refers to a variable pointing to a specific
address in a memory pointed by another variable.
Prepared by Nega Teferra (M.Tech on CSE)
Cont.…
 When you create a variable in your C++ program, it is
assigned some space the computer memory.
 The value of this variable is stored in the assigned location.
 To know the location in the computer memory where the
data is stored, C++ provides the & (reference) operator.
 The operator returns the address that a variable occupies.
 For example, if x is a variable, &x returns the address of
the variable

Pointer Declaration Syntax


datatype *variable_name;
Prepared by Nega Teferra (M.Tech on CSE)
Cont.…

 The datatype is the base type of the pointer which must


be a valid C++ data type.
 The variable_name is should be the name of the pointer
variable.
 Asterisk used above for pointer declaration is similar to
asterisk used to perform multiplication operation.
 It is the asterisk that marks the variable as a pointer.

Prepared by Nega Teferra (M.Tech on CSE)


Reference operator (&)
 When you declare a pointer variable, its content is not initialized.
 In other words, it contains an address of "somewhere", which is
of course not a valid location.
 This is normally done via the address-of operator (&).
 The address-of operator (&) operates on a variable, and returns
the address of the variable.
 For example, if number is an int variable, &number returns the
address of the variable number.
 You can use the address-of operator to get the address of a
variable, and assign the address to a pointer variable.

Prepared by Nega Teferra (M.Tech on CSE)


Cont.…
Example:-
int number = 88; // An int variable with a value
int * pNumber; // Declare a pointer variable called pNumber pointing to an int
pNumber = &number; // Assign the address of the variable number to pointer
 As illustrated, the int variable number, starting at address,
contains an int value 88.
 The expression &number returns the address of the variable
number.
 This address is then assigned to the pointer variable
pNumber, as its initial value.
 The address-of operator (&) can only be used on the RHS.

Prepared by Nega Teferra (M.Tech on CSE)


Dereference operator (*)
• The indirection operator (or dereferencing operator) (*) operates on a pointer,
and returns the value stored in the address kept in the pointer variable.
• For example, if pNumber is an int pointer, *pNumber returns the int value
"pointed to" by pNumber.
Example:
int main()
{
int number = 88;
int * pNumber = &number; // Declare and assign the address of variable number to pointer
cout << pNumber<< endl; // Print the content of the pointer variable, which is an address
cout << *pNumber << endl; // Print the value "pointed to" by the pointer, which is an int (88)
*pNumber = 99; // Assign a value to where the pointer is pointed to, NOT to the
pointer variable
cout << *pNumber << endl; // Print the new value "pointed to" by the pointer (99)
cout << number << endl; // The value of variable number changes as well (99)
}
Prepared by Nega Teferra (M.Tech on CSE)
Cont.…
 Take note that pNumber stores a memory address location, whereas
*pNumber refers to the value stored in the address kept in the pointer
variable, or the value pointed to by the pointer.
 As illustrated, a variable (such as number) directly references a value,
whereas a pointer indirectly references a value through the memory address
it stores.
 Referencing a value indirectly via a pointer is called indirection or
dereferencing.
 The indirection operator (*) can be used in both the RHS (temp = *pNumber)
and the LHS (*pNumber = 99) of an assignment statement.
 Take note that the symbol * has different meaning in a declaration
statement and in an expression.
 When it is used in a declaration (e.g., int * pNumber), it denotes that the
name followed is a pointer variable.
 Whereas when it is used in a expression (e.g., *pNumber = 99; temp <<
*pNumber;), it refers to the value
Prepared pointed
by Nega Teferra (M.Techto by the pointer variable
on CSE)
Pointer has a Type Too
 A pointer is associated with a type (of the value it points to),
which is specified during declaration.
 A pointer can only hold an address of the declared type; it
cannot hold an address of a different type.
int i = 88;
double d = 55.66;
int * iPtr = &i; // int pointer pointing to an int value
double * dPtr = &d; // double pointer pointing to a double value

iPtr = &d; // ERROR, cannot hold address of different type


dPtr = &i; // ERROR
iPtr = i; // ERROR, pointer holds address of an int, NOT int value

int j = 99;
iPtr = &j; // You can change the
Prepared address
by Nega Teferra (M.Techstored
on CSE) in a pointer
Uninitialized Pointers
The following code fragment has a serious logical error!
int * iPtr;
*iPtr = 55;
cout << *iPtr << endl;
 The pointer iPtr was declared without initialization.
 i.e., it is pointing to "somewhere" which is of course an
invalid memory location.
 The *iPtr = 55 corrupts the value of "somewhere"!
 You need to initialize a pointer by assigning it a valid
address.
 Most of the compilers does not signal an error or a warning
for uninitialized pointer?!
Prepared by Nega Teferra (M.Tech on CSE)
Null Pointers
 You can initialize a pointer to 0 or NULL.
i.e., it points to nothing. It is called a null pointer.
 Dereferencing a null pointer (*p) causes an
STATUS_ACCESS_VIOLATION exception.
 int * iPtr = 0; // Declare an int pointer, and initialize the
pointer to point to nothing
 cout << *iPtr << endl; // ERROR! STATUS_ACCESS_VIOLATION
exception
 int * p = NULL; // Also declare a NULL pointer points to
nothing
 Initialize a pointer to null during declaration is a good software
engineering practice
Prepared by Nega Teferra (M.Tech on CSE)
Pointers and Arrays
 Arrays and pointers work based on a related concept.
 There are different things to note when working with
arrays having pointers.
 The array name itself denotes the base address of the
array.
 This means that to assign the address of an array to a
pointer, you should not use an ampersand (&).
We can implicitly convert an array into a pointer. For example:

int arr [20]; p = &arr;


int * ip; This is incorrect.
ip = arr; Prepared by Nega Teferra (M.Tech on CSE)
Cont.…
 After the above declaration, ip and arr will be equivalent, and
they will share properties.
 However, a different address can be assigned to ip, but we
cannot assign anything to arr.

int *ip;
int arr[] = { 10, 34, 13, 76, 5, 46 };
ip = arr;
for (int x = 0; x < 6; x++)
{
cout << *ip << “ ,”;
ip++;
}
Prepared by Nega Teferra (M.Tech on CSE)
Cont.… It is perfectly acceptable to apply the
pointer operator * to var but it is
illegal to modify var value.
const int MAX = 3;
int main () The reason for this is that var is a
{ constant that points to the beginning
int var[MAX] = {10, 100, 200}; of an array and can not be used as l-
for (int i = 0; i < MAX; i++) value.
{ Because an array name generates a
*var = i; // This is a correct syntax pointer constant, it can still be used in
var++; // This is incorrect. pointer-style expressions, as long as it
} is not modified.
return 0;
}
*var=var[0]
*(var+1)=var[1]
*(var + 2) = var[2];

Prepared by Nega Teferra (M.Tech on CSE)


Cont.…
Note
If you add an integer i to the pointer numbers, you will get a
new pointer pointing to the i(th) element of the array.
int a[5] = {10, 20, 30, 40, 50};
for (int i=0; i<5; ++i)
{
cout<<”a[“<<i<<”] = “<<a[i]<<endl;
cout<<”*(a+”<<i<<”) = “<<*(a+i)<<endl;
}

Prepared by Nega Teferra (M.Tech on CSE)


Cont.…
Note
An array name is a constant pointer.
This means that you can not change it to make it point
somewhere else.
int numbers[5];
behaves the same way as const short* numbers;
The const qualifier here tells the compiler that numbers can
not be changed.
However, you can change the value pointed by numbers.

Prepared by Nega Teferra (M.Tech on CSE)


Pointers and String
int main(){
char name[ ]= "Haile";  In this example, since p stores the
char *p;
address of name[0], therefore the value
p = name;
while( *p != '\0') of *p equals the value of name[0] i.e., ‘H'.
{  So in while loop, the first character gets
cout << *p;
p++; printed and p++ increases the value of p
}
by 1 so that now p+1 points to name[1].
return 0;
}  This continues until the pointer reaches
the end of the string i.e., before *p
becomes equal to '\0'.
Prepared by Nega Teferra (M.Tech on CSE)
Pointer Arithmetic
 As you understood pointer is an address which is a numeric
value; therefore, you can perform arithmetic operations on
a pointer just as you can a numeric value.
 There are four arithmetic operators that can be used on
pointers:
++, --, +, and -
 To understand pointer arithmetic, let us consider that ptr
is an integer pointer which points to the address.
 Let us perform the following arithmetic operation on the
pointer.
ptr++

Prepared by Nega Teferra (M.Tech on CSE)


Cont.…
 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.
char Ch[] = "HELLO"; char *str ; str =ch;
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.
H E L L O \0 10 20 30 40

str ptr

str++ ptr++
Prepared by Nega Teferra (M.Tech on CSE)
Incrementing and decrementing a Pointer
 We prefer using a pointer in our program instead of an array because
the variable pointer can be incremented, unlike the array name which
cannot be incremented because it is a constant pointer.
 The same considerations apply to decrementing a pointer, which
decreases its value by the number of bytes of its data type
int main () int main ()
{ {
int var[MAX] = {10, 100, 200}; int var[MAX] = {10, 100, 200};
int *ptr; int *ptr;
ptr = var; ptr = &var[MAX-1];
for (int i = 0; i < MAX; i++) for (int i = MAX; i > 0; i--)
{ {
cout << "Value of var[" << i << "] = "; cout << "Value of var[" << i << "] = ";
cout << *ptr << endl; cout << *ptr << endl;
ptr++; ptr--;
} }
} } Prepared by Nega Teferra (M.Tech on CSE)
Comparing Pointers
 Pointers may be compared by using any of C++’s relational
operators:
>, <, ==, !=, >=, <=
 If one address comes before another address in memory,
the first address is considered “less than” the second.
 This two are different
if (ptr1 < ptr2) // Comparing the Address
if (*ptr1 < *ptr2) //Comparing the pointed value

Prepared by Nega Teferra (M.Tech on CSE)


Pointer to Pointer (Multiple Indirection)
 A pointer to a pointer is a form of multiple indirection or a
chain of pointers.
 Normally, a pointer contains the address of a variable.
 When we define a pointer to a pointer, the first pointer
contains the address of the second pointer, which points to
the location that contains the actual value.
 A variable that is a pointer to a pointer must be declared
as such.
 This is done by placing an additional asterisk in front of its
name
Example: int **ptr;
Prepared by Nega Teferra (M.Tech on CSE)
Cont.…
 When a target value is indirectly pointed to by a pointer to a pointer,
accessing that value requires that the asterisk operator be applied twice

int main()
{
int var =30;
int *ptr,**pptr;
ptr = &var;
pptr = &ptr;
cout << "Value of var :" <<var<< endl;
cout << "Value available at *ptr :"<<*ptr<<endl;
cout << "Value available at **pptr :" <<**pptr<< endl;
return 0;
}

Prepared by Nega Teferra (M.Tech on CSE)


Pointers as Function Parameters
 C++ allows you to pass a pointer to a function.
 To do so, simply declare the function parameter as a
pointer type.
 The call by reference method of passing arguments to a
function copies the reference of an argument into the formal
parameter.
 Inside the function, the reference is used to access the actual
argument used in the call.
 This means that changes made to the parameter affect the
passed argument.
 To pass the value by reference, argument reference is passed
to the functions just like any other value.
Prepared by Nega Teferra (M.Tech on CSE)
Cont.…
void swap(int &x, int &y) int main ()
{ {
int a = 11;
int temp; int b = 33;
temp = x; cout << "Before swap, value of a :" << a << endl;
x = y; cout << "Before swap, value of b :" << b << endl;
y = temp; swap(a, b);
return; cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
} return 0;
}

Prepared by Nega Teferra (M.Tech on CSE)


Cont.…
 Since we have done this swapping with pointers ( we have
targeted on address ), so, this interchanged value will also
reflect outside the function and the values of 'a' and 'b'
will also get interchanged.
 In the above example, we passed the address of the two
variables (a and b) to the swap function.
 The address of a is stored in 'x' pointer and that of b in
'y' pointer.
 In the swap function, we declared a third variable 'temp'
and the values of 'x' and 'y' (and thus that of a and b) gets
swapped.

Prepared by Nega Teferra (M.Tech on CSE)


Passing an entire Array in a Function
 We can also pass a whole array to a function by passing the array name as
argument.
 Yes, the trick is that we will pass the address of array, that is the address
of the first element of the array.
 Thus, by having the pointer of the first element, we can get the entire array

Prepared by Nega Teferra (M.Tech on CSE)


Example void display(int *p,int s)
{
int main(){ cout<<endl;
int size; for(int i=0;i<s;++i)
cout << "Enter the size of array" << {
endl; cout << "n[" << i << "] = " << *p <<
cin >> size; endl;
int n[size]; p++;
for(int j=0; j<size; j++) }
{ }
cout << "Value of n[" << j << "] : ";
cin >> n[j];
}
display(n,size);
return 0;
}
Prepared by Nega Teferra (M.Tech on CSE)
Passing a string in a Function
The concept of functions returning pointers of strings is handled in the
same fashion we handling arrays.
int main()
#include <iostream> {
#include<string.h> char name[10],pswd[10];
using namespace std; cout<<"Enter your username:\n";
cin>>name;
void authentication(char *ch,char *ps)
cout<<"Enter your password:\n";
{ cin>>pswd;
char usrnm[10]="Haile", usrps[10]="Teddy"; authentication(name,pswd);
cout<<endl; return 0;
if(strcmp(usrnm,ch)==0 && strcmp(usrps,ps)==0) }
{
cout<<"Username: "<<ch<<endl;
cout<<"Password: "<<ps<<endl;
}
else
cout<<"Wrong username or password!";
}
Prepared by Nega Teferra (M.Tech on CSE)
Dynamic Memory
 A program can create its own variables during runtime.
 This is called dynamic memory allocation and it is possible
only through the use of pointers.
 The program asks the computer to set aside some memory
for a variable.
 The computer fulfills this request and gives the program
the starting address of the reserved memory.
 The program can only access the newly allocated memory
through its address.

Prepared by Nega Teferra (M.Tech on CSE)


The new Operator
 The request is made through the new operator.
int *intPtr;
intPtr = new int;
 The second statement is requesting that the computer allocate
enough memory for a new int variable.
 The operand of the new operator is the data type of the variable
being created.

 The new variable is accessed and used through the pointer.


int *intPtr = new int;
*intPtr = 5;
cout<<*intPtr<<endl;
*intPtr += 12; //etcetera
Prepared by Nega Teferra (M.Tech on CSE)
Dynamically Creating an Array
 Similarly, we can create an array dynamically using the new
operator.
int *myArray = new int[400];
 Or, more importantly,
int n;
cout<<”Enter the size of the array: “;
cin>>n; int *myArray = new int[n];
 myArray can now be accessed like any other array.

Prepared by Nega Teferra (M.Tech on CSE)


The delete Operator

 When a program is finished using a dynamically allocated


chunk of memory, it should release it for future use.
 The delete operator is used to free memory that was
allocated with new.
 To free a single variable,
delete intPtr;
 To free an array
delete [] myArray;

Prepared by Nega Teferra (M.Tech on CSE)


Cont.…

Prepared by Nega Teferra (M.Tech on CSE)

You might also like