0% found this document useful (0 votes)
40 views46 pages

Chapter 3. Pointers

Uploaded by

Teshale Siyum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views46 pages

Chapter 3. Pointers

Uploaded by

Teshale Siyum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Fundamentals of Programming in C++

CoSc 2031

Chapter 3

Pointer

Mekonnen K.
1
(MSc) Email: [email protected]
Objectives:
• Pointer Data Type and Pointer Variables
• Pointer Declaration
• Pointer Operators
• Initializing Pointer Variables
• Operations, Expressions and Arithmetic on Pointer Variables
• Strings and pointers
• Relationship between pointers & arrays
• Functions and Pointers
• Dynamic memory management
2
What is Pointer

 A pointer is a variable that stores a memory

address. Pointers are used to store the addresses of

other variables or memory items. Pointers are very

useful for another type of parameter passing, usually

referred to as Pass By Address. Pointers are

essential for dynamic memory allocation.

3
Pointer Data Type and Pointer Variables

 C++’s data types are classified into three categories:

 Simple

 Structured

 Pointers.

4
What is the Pointer Value

5
Pointer Data Type and Pointer Variables

 There is no name associated with pointer data types


 If no name is associated with a pointer data type, how
do you declare pointer variables?

 p is called a pointer variable of type int


 ch is called a pointer variable of type char.

6
Pointer Declaration
 Thus, the character * can appear anywhere between the
data type name and the variable name.

int int* int *


*p; p; p;

7
Pointer Declaration
 int* p, q;

 In this statement:
 only p is the pointer variable, not q.

 Here, q is an int variable.

 we prefer to attach the character * to the variable name.


So the preceding statement is written as:

int *p, q;

8
Pointer Operators
 C++ provides two operators operator to work with
pointers.

 (&) the address of operator

 (*) the dereferencing

9
Address of Operator (&)
 is a unary operator that returns the address of its
operand.
 For example, given the statements:
int x;
int *p;
 The statement:
p = &x;
 assigns the address of x to p. That is, x and the value of p
refer to the same memory location

10
Dereferencing Operator (*)
 referred to as indirection operator

 refers to the object to which its operand (that is, the


pointer) points.

 For example, given the statements:


p X
25

11
Dereferencing Operator (*)
 Let us consider the following statements:

In these statements:
 p is a pointer variable of type int
 num is a variable of type int.

 Let us assume that memory location 1200 is allocated for p,


and memory location 1800 is allocated for num.

12
Dereferencing Operator (*)

 Consider the following statements.

1. num = 78;

2. p = #

3. *p = 24;

13
Example
#include <iostream>
#include <string>
using namespace std;
//===============================
int main() {
int *p;
int x = 37;
cout <<"x= " << x<<endl;
p=&x;
cout <<"*p= "<< *p <<" , x= "<<x<<endl;
*p=85;
cout <<"*P= " <<*p <<" , x= "<<x<<endl;
cout <<" Address of p is : "<< &p <<endl;
cout<<"value of p : "<< p<<endl;
cout<< " value of memory location pointed to by *p = "<<*p<<endl;
cout<<"Address of X = " << &x<<endl;
cout <<" Value of x = " << x<<endl;
return 0;
}

14
15
Summary:

16
Initializing Pointer Variables
 C++ does not automatically initialize variables
 pointer variables must be initialized if you do not want them
to point to anything.
 Pointer variables are initialized using the following two
statements :
 p = NULL;
 p=0;

 The number 0 is the only number that can be directly assigned


to a pointer variable.
17
Operations on Pointer Variables
 There are four arithmetic operators that can be used on pointers:
 Increment ++
 Decrement --
 Addition +
 Subtraction -
 The following operation can be performed on pointers.
 We can add integer value to a pointer.
 We can subtract an integer value from a pointer.
 We can compare two pointers, if they point the elements of the
same array.
 We can subtract one pointer from another pointer if both point to
the same array.
 We can assign one pointer to another pointer provided both are of
same type.
18
Operations on Pointer Variables
 The following operations cannot be performed on pointers

 Addition of two pointers.

 Subtraction of one pointer from another pointer when they


do not point to the same array.

 Multiplication of two pointers.

 Division of two pointers.

19
Operations on Pointer Variables

 copies the value of q into p. After this statement executes,


both p and q point to the same memory location.

 Any changes made to *p automatically change the value of


*q, and vice versa.
20
Comparison
The expression:
 p == q
evaluates to true if p and q have the same value—that is, if
they point to the same memory location.
Similarly, the expression:
 p != q
evaluates to true if p and q point to different memory
locations.
21
Decrement and increment
 ++ increments the value of a pointer variable by the size of
the memory to which it is pointing.
 Similarly, -- the value of a pointer variable by the size of the
memory to which it is pointing.
 to explain the increment and decrement operations on
pointer variables:

Recall that the size of the memory allocated for an


 int variable is 4 bytes
 a double variable is 8 bytes
 a char variable is 1 byte.
 studentType is 40 bytes.
22
Decrement and increment
The statement:
 p++; or p = p + 1;
increments the value of p by 4 bytes because p is a pointer of
type int.
Similarly, the statements:
 q++;
 chPtr++;
increment the value of q by 8 bytes and the value of chPtr by 1
byte, respectively.
The statement:
 stdPtr++;
increments the value of stdPtr by 40 bytes.

23
Cont.
 Moreover, the statement:
 p = p + 2;
 increments the value of p by 8 bytes.
 Thus, when an integer is added to a pointer variable, the value
of the pointer variable is incremented by the integer times the
size of the memory that the pointer is pointing to.
 Similarly, when an integer is subtracted from a pointer variable,
the value of the pointer variable is decremented by the integer
times the size of the memory to which the pointer is pointing.

24
Notes
 Pointer arithmetic can be very dangerous.

 The program can accidentally access the memory


locations of other variables and change their content
without warning. leaving the programmer trying to find
out what went wrong.

25
Example.
 A program to illustrate the pointer expression and pointer arithmetic.
#include<iostream.h>
void main( )
{
int a, b, x, y;
int *ptr1, *ptr2;
a = 30;
b = 6;
ptr1 = &a
ptr2 = &b;
x = *ptr1 + *ptr2 – 6;
y = 6 - *ptr1 / *ptr2 + 30;
cout<<”Address of a = “<<ptr1<<endl;
cout<<”Address of b = “<<ptr2<<endl;
cout<<”a = “<<a<<”b = “<<b<<endl;
cout<<”x = “<<x<<”y = “<<y<<endl;
*ptr1 = *ptr1 + 70;
*ptr2 = *ptr2 * 2
26 cout<<”a = “<<a<<”b = “<<b<<endl;
}
Pointers and arrays
 There is a close relationship between array and pointers in
C++.
 Consider the following program which prints the elements of
an array A.
 #include<iostream.h>
void main( )
{
int A[5] = { 15, 25, 67, 83, 12};
for (int i = 0; i<5; i++)
cout<<A[i]<<”\t”;
}
 Output of the above program is: 15 25 67 83 12

27
Pointers and arrays
 When we declare an array, its name is treated as a constant
pointer to the first element of the array.
 This is also known as the base address of the array.
 In other words base address is the address of the first element
in the array of the address of a[0].
 If we use constant pointer to print array elements.
 #include<iostream.h>
void main( )
{
int A[5] = { 15, 25, 67, 83, 12};
cout<< *(A) <<”\t”;
cout<< *(A+1) <<”\t”;
cout<< *(A+2) <<”\t”;
cout<< *(A+3) <<”\t”;
cout<< *(A+4) <<”\t”;
}
28
 Output of the above program is: 15 25 67 83 12
Pointers and arrays
 Here the expression *(A+3) has exactly same effect as A[3] in
the program.

 The difference between constant pointer and the pointer


variable is that the constant pointer cannot be incremented or
changed while the pointer to an array which carries the
address of the first element of the array may be incremented.

29
Pointers and arrays
 The following example shows the relationship between pointer and
one dimensional array.
 #include<iostream.h>
void main( )
{
int a[10], i, n;
cout<<”Enter the input for array”;
cin>>n;
cout<<”Enter array elements:”;
for(i=0; i<n; i++)
cin>>*(a+i);
cout<<The given array elements are :”;
for(i=0; i<n; i++)
cout<<”\t”<<*(a+i);
}
30
Pointers and string
 String is sequence of characters ends with null (“\0”) character.

 C++ provides two methods of declaring and initializing a string.


 Method 1:
 char str1[ ] = “HELLO”;

 When a string is declared using an array, the compiler reserves one


element longer than the number of characters in the string to
accommodate NULL character.
 The string str1[ ] is 6 bytes long to initialize its first 5 characters
HELLO\0.
 Method 2:
 char *str2 = “HELLO”;
31
Pointers and string
 C++ treats string constants like other array and interrupts a
string constant as a pointer to the first character of the string.
 This means that we can assign a string constant to a pointer
that point to a char.
 Example: A program to illustrate the difference between
strings as arrays and pointers.
 #include<iostream.h>
void main( )
{
char str1[ ] = “HELLO”;
char *str2 = “HELLO”;
cout<<str1<<endl;
cout<<str2<<endl;
str2++;
cout<<str2<<endl;
}
32
Functions and Pointers
 A pointer variable can be passed as a parameter to a function
either by value or by reference.

 In the function pointerParameters, both p and q are pointers.


The parameter p is a reference parameter; the parameter q is
a value parameter.

 Furthermore, the function pointerParameters can change the


value of *q, but not the value of q. However, the function
pointerParameters can change the value of both p and *p.

33
Example
#include <iostream>
using namespace std;
void f(int *j);
int main()
{
int i =0 ;
int *p;
p = &i; // p now points to i
cout<<"*p is " << *p<<endl
<< "i= " << i <<endl;
f(p);
cout << "i is " << i << endl;
return 0;
}
void f(int *j)
{
*j = 100; // var pointed to by j is assigned 100
cout <<"*j is : "<< *j<<endl;
}
34
Functions and Pointers
 Passing a pointer as an argument to a function is in some
ways similar to passing a reference.

 They both permit the variable in the calling program to


be modified by the function.

 However, the mechanism is different. A reference is an


alias for the original variable, while a pointer is the
address of the variable.

35
Pointers and Function Return Values
 In C++, the return type of a function can be a pointer. For
example, the return type of the function:

36
Example
#include <iostream>
using namespace std;
double * GetSalary()
{
double salary = 26.48;
double *HourlySalary = &salary;
return HourlySalary;
}
int main()
{
double hours = 46.50;
double salary = *GetSalary();
cout << "Weekly Hours: " << hours << endl;
cout << "Hourly Salary: " << salary << endl;
double WeeklySalary = hours * salary;
cout << "Weekly Salary: " << WeeklySalary << endl;
return 0;
}
37
38
Memory Allocation of Pointers
 Memory Allocation is done in two ways:
o Static Allocation of memory
o Dynamic allocation of memory.

 Static Allocation of Memory:


 Static memory allocation refers to the process of allocating memory
during the compilation of the
program i.e. before the program is executed.

 Example:

 int a; // Allocates 2 bytes of memory space during the compilation.

39
Memory Allocation of Pointers
 Dynamic Allocation of Memory:
 Dynamic memory allocation refers to the process of allocating
memory during the execution of the program or at run time.
 Memory space allocated with this method is not fixed.
 C++ supports dynamic allocation and de-allocation of objects using
new and delete operators.
 These operators allocate memory for objects from a pool called the
free store.
 The new operator calls the special function operator new and
delete operators call the special function operator delete.

40
New Operator
 We can allocate storage for a variable while program is
running by using new operator.
 It is used to allocate memory without having to define
variables and then make pointers point to them.
 The following code demonstrates how to allocate memory for
different variables.
 To allocate memory type integer
 int * pnumber;
 pnumber = new int;
41
New Operator
 The first line declares the pointer, pnumber. The second line
then allocates memory for an integer and then makes
pnumber point to this new memory.

 To allocate memory for array,


 double *dptr = new double[25];

 To allocates dynamic structure variables or objects,


 student sp = new student

42
Delete Operator
 The delete operator is used to destroy the variables space
which has been created by using the new operator dynamically.

 Use delete operator to free dynamic memory as :


 delete iptr;

 To free dynamic array memory:


 delete [] dptr;

 To free dynamic structure,


 delete structure;

43
Difference between Static and Dynamic
Memory Allocation

Sl no Static Memory Dynamic Memory


Allocation Allocation
1. Memory space is allocated Memory space is allocated during
before the execution of the execution of program.
program.
2. Memory space allocated is fixed Memory space allocated is not
fixed
3. More memory space is required Less memory space is required.

4. Memory allocation from stack Memory space form heap area.


area

44
Free store (Heap memory)
 Free store is a pool of memory available to allocated and
de-allocated storage for the objects during the execution
of the memory.

 Memory Leak:
 If the objects, that are allocated memory dynamically, are not
deleted using delete, the memory block remains occupied even
at the end of the program.
 Such memory blocks are known as orphaned memory blocks.
 These orphaned memory blocks when increases in number,
bring adverse effect on the system. This situation is called
memory leak.
45
46

You might also like