0% found this document useful (0 votes)
18 views22 pages

Pointers in C++

Uploaded by

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

Pointers in C++

Uploaded by

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

Pointers in C++

Topics to cover:

• Overview of Pointers
• Pointer Declaration
• Pointer Assignment
• Pointer Arithmetic
• Relations Between Pointers and Arrays
• Pointers and Strings

1
Overview of Pointers

• A Pointer in C++ is variable whose value is a memory


address.
• With pointers many memory locations can be
referenced.
• Some data structures use pointers (e.g. linked list,
tree).
• The * and & operators
- & operator is the address operator
- * operator is the dereferencing operator. It is used in
pointers declaration

2
Pointer Declaration

• Pointers are declared as follows:


<type> * variable_name ;
e.g.
int * xPtr; // xPtr is a pointer to data of type integer

char * cPtr; //cPtr is a pointer to data of type character

void * yPtr; // yPtr is a generic pointer,


// represents any type

3
Pointer Assignment
• Assignment can be applied on pointers of the same type
• If not the same type, a cast operator must be used
• Exception: pointer to void does not need casting to convert a
pointer to void type
• void pointers cannot be dereferenced
• Example
int *xPtr, *yPtr; int x = 5;

xPtr = & x; // xPtr now points to address of x
yPtr = xPtr; // now yPtr and xPtr point to x

4
Pointer Arithmetic

• Increment / decrement pointers ( ++ or -- )


• Add / subtract an integer to/from a pointer
( + or += , - or -= )
• Pointers may be subtracted from each other
• Pointer arithmetic is meaningless unless
performed on an array

5
Pointer Arithmetic (Cont.)
• Example
Consider an integer array of 5 elements on a machine using 4 bytes for
integers.
1000 1004 1008 1012 1016

V[0] V[1] V[2] V[3] V[4]

Pointer variable vPtr

- vPtr pointes to first element V[0] (location 1000)


i.e. vPtr = 1000
- vPtr +=2; sets vPtr to 1008
i.e. vPtr points to V[2]

6
Pointer Arithmetic (Cont.)

• Subtracting pointers
- Returns the number of elements between two
addresses

e.g. if v is an array and


vPtr1 = v[1];
vPtr2 = v[2];
then vPtr2 – vPtr1 = 2 (i.e. 2 addresses)

7
Relations Between Pointers and Arrays

• Arrays and pointers are closely related.


- Array name is like constant pointer
- Pointers can do array subscribing operations
- If we declare an array A[4] and a pointer aPtr
 aPtr is equal to A
aPtr == A
 aPtr is equal to the address of the first
element of A
aPtr == & A[0]

8
Relations Between Pointers and Arrays (Cont.)

• Accessing array elements with pointers:


- Element A[i] can be accessed by *(aPtr+i)
 This is called pointer/offset notation
- Array itself can use pointer arithmetic
 A[3] is same as *(A+3)
- Pointers can be subscripted
(i.e. pointer/subscript notation)
 aPtr [3] is same as A[3]

9
Examples on Pointers
//File: swap.cpp
//A program to call a function to swap two numbers using reference
parameters

#include <iostream.h>
void swap(int *, int *); // This is swap's prototype
void main()
{ int x = 5, y = 7;
swap(&x , &y); // calling swap with reference parameters
cout << "\n x is now "<< x << " and y is now " << y << '\n';
}
// swap function is defined here using dereferencing operator ‘*’
void swap(int *a, int *b)
{ int temp;
temp = *a;
*a = *b;
*b = temp;
}
10
Examples on Pointers (Cont.)
//File: pointers.cpp
//A program to test pointers and references
#include <iostream.h>
void main ( )
{ int intVar = 10;
int *intPtr; // intPtr is a pointer
intPtr = & intVar;
cout << "\nLocation of intVar: " << & intVar;
cout << "\nContents of intVar: " << intVar;
cout << "\nLocation of intPtr: " << & intPtr;
cout << "\nContents of intPtr: " << intPtr;
cout << "\nThe value that intPtr points to: " << * intPtr;
}

11
Pointers and Strings

• Pointers can be used to declare strings and with string


functions.

12
When calling, the pointer formal parameter will points to
the actual parameter

#include <iostream.h>
void Increment(int*);
main() {
int A = 10; O/p----11 if we use ++X (o/p10)

Increment(&A);
cout<<A<<endl;
}
void Increment(int *X)
{
++*X;
} 13
Dynamic Memory allocation
• Every program needs storage to be allocated to it for
various purposes.
• When you write a program, you specify what storage
it needs by declaring variables and instances of
classes, e.g:
int a,b,c;
float nums[100];
Circle myCircle(2.0,3,3); etc...
• Then when the program executes, it can make use of
this memory
• It is not possible for variables or objects to be added
during the execution of a program
Programs and Memory
• In order to execute a program, it must be loaded into
RAM (Random Access Memory).
• A certain amount of RAM is allocated as the
permanent storage for your program, and this is where
the global variables are stored.
• A dynamic region of memory called the stack, where
local variables are stored.
• This storage is fixed at compile time.
Global variables hold their value for the lifetime of
the program, while local variables only hold their
value for the lifetime of the function they are
declared in.
• For example, you may want to write a program that
reads in a list of numbers (until 999 is entered) and
finds their average.
• You may want to store the numbers in an array, but of
what size?
• Each time the program is run, the user may enter any
number of numbers, maybe 5, 50 or 5000.
• One solution is to declare an array of the maximum
size that it could ever be. e.g int nums[10000].
• However, this is wasteful of memory, as you may use
only a fraction of the space allocated.
• The solution is to use dynamic allocation of
memory.
• This is the means by which a program can obtain
memory while it is running.
• Powerful support for dynamic memory allocation is
provided in C++, with the operator new.
• C++ also provides the operator delete, which releases
the memory once the program doesn't need it
anymore.
The new operator
• The new operator returns a pointer to allocated
memory from the heap.
• It returns a NULL pointer if there is insufficient
memory to fulfill the allocation request.
• The delete operator frees memory previously allocated
using new.
• Example of usage:
int *ptr; //Pointer that can point to an integer
ptr = new int; //Now it points to allocated
memory
Example: new
int main()
{
int*ptr; //Pointer that can point to an integer
ptr = new int; //Now it points to allocated memory
if(!ptr) //NULL pointer returned
{
cout << "Allocation error\n";
}
else
{
*ptr = 100;
cout <<"Memory location: "<< ptr;
cout <<" contains the int value: "<< *ptr <<endl;
delete ptr; //deallocate the memory
}}
Example: new with initialisation
int *ptr; //Pointer that can point to an integer
ptr = new int(87);
//Allocate memory and initialize to 87

if(!ptr) //NULL pointer returned


{
cout << "Allocation error\n";
}
else
{
cout <<"Memory location: "<< ptr;
cout <<" contains the int value: "<< *ptr <<endl;
delete ptr; //deallocate the memory
}
Allocating arrays

• You can allocate one-dimensional arrays using new as


follows:
int *ptr;
ptr = new int[10];
• You may then use the pointer as you would a normal
array.
• You may not specify an initializer when allocating
arrays.
• When an array allocated by using new is released,
delete must be told that it is an array. E.g:
delete [] ptr;
int *ptr;
int inum; Example:
cout<<"How many numbers will you enter?: "; new with arrays.
cin>> inum;

ptr = new int[inum];

if(!ptr)
cout<<" Allocation Error!\n";
else
{
for(int i=0;i<inum;i++)
{
cout<< "Enter number: ";
cin>>ptr[i];
}
/*
* .....Do some processing to the array .......
*/
delete [ ] ptr; //Release 10 elements
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy