0% found this document useful (0 votes)
17 views

Problem Solving IChapter 5

This document discusses pointers in C++. It defines what a pointer is, how to declare and initialize pointer variables, and how to dereference pointers to access the variable being pointed to. It also covers pointer arithmetic, relational operations, and the difference between const pointers and pointers to const.

Uploaded by

Alemayew Azezew
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Problem Solving IChapter 5

This document discusses pointers in C++. It defines what a pointer is, how to declare and initialize pointer variables, and how to dereference pointers to access the variable being pointed to. It also covers pointer arithmetic, relational operations, and the difference between const pointers and pointers to const.

Uploaded by

Alemayew Azezew
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

CS221 : Computer Programming I

Chapter 5 : Pointer

1
Pointer-Concept
The memory of your computer can be 000A1051 6
imagined as a succession of memory 000A1052
000A1053
cells, each one of the minimal size that
000A1054 2
computers manage (one byte).
000A1055
These single-byte memory cells are 000A1056
numbered in consecutive way. This 000A1057 7
number is called the address of that 000A1058
byte. Hexadecimal number is used to 000A1059
1
represent these addresses. 000A1060
000A1061 0

000A1062
8
000A1063
000A1064
000A1065
2
Pointer and Variable
A variable is implemented as a sequence of
adjacent memory locations. For example
float var1=27.34;
char var2=‘A’; short var3; 000A1051 A
Char
var1 is implemented as 4 bytes of 000A1052 var2
000A1053
consecutive memory. 27.34
000A1054
var2 is implemented as 1 bytes of memory. 000A1055
Float
var3 is implemented as 2 bytes of 000A1055
var1
000A1056
consecutive memory
000A1057
The memory address of the first byte 000A1058
can be used as names for the variables. 000A1059
10
short
Thus a pointer to the memory address 000A1060 var3
b
000A1061
of the first byte of the variable provides c
000A1062
an indirect way of accessing variable. 000A1063
000A1064
3
Pointer Type

A pointer data type is a derived data type whose value may


be any of the memory address available in the computer.
A pointer data type is a data type for containing an address
rather than a data value.
It is integral, similar to int.
The size depends on the number of bytes in which the target
computer stores a memory address(usually 4 bytes)

4
Pointer Value
C++ allows you to obtain the memory
address of the first byte of a variable, i.e. 000A1051 A
char
the pointer to the variable, through the 000A1052
address operator(&). 000A1053
000A1054 27.34
The address operator(&) provides a pointer
000A1055
constant to any named location in memory. 000A1055 Float
var1
Syntax: 000A1056
000A1057
&var_name
000A1058
Where var_name is a valid variable name. 10
000A1059 short
Example: consider the previous slide and 000A1060 var3
b
what will be printed 000A1061
c
float var1=27.34; 000A1062
000A1063
char var2=‘A’; 000A1064
cout << “Address of var1: “ << &var1 << ‘\n’; 5

cout << “Address of var2: “ << &var2 << ‘\n’ ’;


Pointer Variable

Even though a pointer value is a memory address and a


memory address is a number, you cannot store a pointer in a
variable of type int or double.
A pointer variable is a variable that allows to store and
manipulate a pointer values(address of a variable).

6
Declaring a Pointer Variable
Like any other variable a pointer variable should be declared prior of
use.
Different types uses different numbers of bytes and different internal
formats for storing values. Therefore, a pointer declaration must
specify what type of data to which the pointer points.
Declaration syntax:
dataType * ptr1, * ptr2, …,* ptrLast;
The variable ptr1, ptr2,…ptrLast can hold pointers to variables of type
dataType only but it cannot normally contain a pointer to a variable
of some other type.
Example:
double * ptrSale; //ptrSale is a pointer variable that can point a
double variable
int *p1, *p2, v1, v2; //p1, p2 are pointers, v1,v2 are int
7
Pointer Initialization
You can use the address operator & to determine the address of a
variable, and you can then assign that address to a pointer variable.
A pointer can be initialized during declaration by assigning it the address
of an existing variable. Then it is said to be it points to that variable.
SYNTAX
dataType var1, var2,…, varLast;
dataType *pvar1=&var1, *pvar2=&var2, …, *pvarLast=&varLast;
EXAMPLE
float data = 50.8;
float *ptr = &data; //ptr points to data
ptr Data
A pointer can be initialized to a NULL(0) during declaration . Then it is
said to be it points to nothing.
int *ip = 0;// points to nothing
float *fp = NULL; // points to nothing 8
Pointer Initia…
Pointers can also be initialized or set a value after declaration.
Example:
int ival1; fptr1 fval1

float fval1; fptr2


int * iptr1, *iptr2;
iptr1 ival1
float *fptr1,*fptr2 ;
fptr1=&fval1;//fptr1 points to fval1
fptr2=fptr1;
fptr2=0; //fptr1 points to nothing
iptr1=&ival1; //iptr points to ival1
iptr2=&fval1; //invalid assignment!!
Note: For a type T, T* is the type “pointer to T”. That is, a variable
of type T* can hold the address of an object of type T. 9
Accessing Variables Through Pointers

Pointers stores a reference to another variable. Pointers are


said to "point to" the variable whose reference they store.
Using a pointer we can indirectly access the value stored in
the variable which it points to. C++ provides the indirection
(or dereference)operator(*) for doing this.
Syntax:
*ptr_variable
Where ptr_variable is a pointer variable.

10
Accessing…
EXAMPLE
double x=0; *ptr1, *ptr2;
ptr1=&x;
ptr2=ptr1;
cout << x;
cout << *ptr1;
cout << *ptr2; The three statements are equivalent,
*ptr1=6;
cout << x << “ “ << *ptr2; //What is the output?
Note:
• It is an error to dereference a pointer whose value is NULL. It is
recommended first to check for NULL before dereferencing
• your program may also crash with run time error if you try to
dereference uninitialized pointer variable. 11
Pointer Operation
• Assignment – the value of one pointer variable can be assigned to
another pointer variable of the same type. Example:
int *ptr1, *ptr2, ival=0;
float *ptr3,fval=5;
ptr1=&val; //valid?
ptr1=&fval; // valid?
ptr3=ptr1; // valid?
ptr2=&ptr1;// valid?
ptr3=fval; // valid?
ptr3=&fval; // valid?
ptr1= 0xB8000000; // valid?
ptr1= (int *) 0xB8000000; // valid?
• Some limited arithmetic operations
– integer values can be added to and subtracted from a pointer
variable
ptr2=ptr1 + 5; ptr2=ptr1 - 5
12
Pointer Operation

– value of one pointer variable can be subtracted from


another pointer variable of the same type
int noElem=ptr2 –ptr1;
– Increment and decrement operation are valid.
ptr++, ptr--, ++ptr, --ptr
– Other arithmetic operation are not allowed
• Relational operations - two pointer variables of the same type
can be compared for equality, and so on
ptr1 <= ptr2; ptr1==ptr2
The most common is checking a pointer for NULL
if(ptr == NULL) equivalent to if(!ptr)
if(ptr != NULL) equivalent to if(ptr)
13
Const Modifiers and Pointers
The use of the const modifier with pointers is confusing as it can mean
two things
– const int* cptrInt; // cptrInt is a pointer to a const int
You can not change the value of the integer that cptrInt points to but
you can change the pointer itself
– int* const ptrcInt; // ptrcInt is a constant pointer to int
You can change the value of the integer that ptrcInt points to but
you can not change the pointer itself
Example:
double x=6.8, y=8.6;
const double *ptr1=&x;
double* const ptr2=&x;
ptr2=ptr1; // Is it valid?
*ptr1=8.7; // Is it valid?
14
Pointer and Array
There is a close association between pointers and arrays
The name of an array is also a constant pointer to the first element
of the array. Therefore an array element can be accessed using the
dereference operator. Thus
arr[3] is equivalent to *(arr +3)
The offset operator([]) that we used to access the elements of an
array is another dereference operator. They dereference the variable
they follow just as * does, but they also add the number(offset)
between brackets to the address being dereferenced.
Thus if a pointer p pointes to the first element of the array arr, it is
possible to access the elements of the array through the pointer
using the dereference operator or the offset operator
*(p +3) is equivalent to p[3]// access the fourth element

15
Pointer and…

int array[5] = { 23, 5, 12, 34, 17 }; // array of 5 ints


for (int i=0; i< 5; i++)
cout << array[i] << endl; //using offset operator to access elements
for (int i=0; i< 5; i++)
cout << *(array+i) << endl; //using pointer version to access elements
int *arrPtr=array;
for (int i=0; i< 5; i++)
cout << arrPtr[i] << endl; using pointer to access elements
Note: Although an array name is a pointer, it can not be assigned
because it is a constant pointer.
array=arrPtr; //Invalid even if both array and arrPtr point to the
same type
16
Example

Write a program that reverses the elements of one


dimensional array without using another array. Use pointer
concept to traverse the array.

17
Example

Write a program that an array elements are palindrome. Use


pointer concept to traverse the array.

18
Void Pointer
The void type of pointer is a special type of pointer. In C++, void
represents the absence of type, so void pointers are pointers that
point to a value that has no type (and thus also an undetermined
length and undetermined dereference properties).
The void pointer, also known as the generic pointer, is a special
type of pointer that can be pointed at objects of any data type. A
void pointer is declared like a normal pointer, using the void
keyword.
Syntax:
void * voidPtr;
Example:
int val1=6; float val2=3.14;
void * voidPtr=&val1;
voidPtr=&val2;
19
Void Pointer

The programmer must note that void pointers cannot be de-


referenced in the same manner as other pointers.
Direct dereferencing of void pointer is not permitted.
The programmer must change the pointer to void as any
other pointer type that points to valid data types such as, int,
char, float and then dereference it.
cout << *((float *) voidPtr); //the void pointer is casted to
//float pointer then dereferenced.

20
Void Pointer
#include <iostream.h>
#include <conio.h>
int main()
{
int inum[3] = {10,20,30},i;
float fnum[4] = {1.2, 2.4, 3.7,9.8};
void *pvoid = NULL;
pvoid = inum;
for ( i=0; i<3; i++ )
cout<<*((int *)pvoid + i );
// Same void pointer can be cast to float
cout<<"\n";
pvoid = fnum;
for( i=0; i < 4; i++ )
cout<< *((float *) pvoid + i));
getch();
21
}
Pointer to Pointer
C++ allows the use of pointers that point to pointers, that these, in
its turn, point to data (or even to other pointers). In order to do
that, we only need to add an asterisk (*) for each level of reference
in their declarations:
Example:
char a; // a is type char
char * b; //b is type a pointer to char
char ** c; //c is type a pointer to pointer to char
char ***d; //d is type a pointer to pointer to pointer to char
a = 'z';
b = &a; supposing the randomly chosen memory locations for each variable are
7230, 8092 and 9002, it could be represented as:
c = &b;
a b c d
d=&c;
z 7230 9002 10012
22
7230 9002 10012 30012
Pointer to…
#include <iostream.h>
int main()
{
int num = 26;
int *ptr;
int **ptrToPtr;
ptr = &num;
ptrToPtr = &ptr;
cout << " The value of num is: = " << num << "\n";
cout << " The value of num is: = “ << *ptr << "\n";
cout << " The value of numis: = “ << **ptrToPtr << "\n";
return 0;
}
23

You might also like