Pointers in C++

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 26

Pointers in C++

Amela Nuhanović
Introduction

● A pointer is a variable that stores the memory address as its value


● Pointer variable points to a data type (like int or string) of the same
type
● Pointer is created with the * operator
Example
string food = "Pizza"; // A food variable of type string

string* ptr = &food; // A pointer variable, with the name ptr, that stores the address of food

// Output the value of food (Pizza)

cout << food << "\n";

// Output the memory address of food (0x6dfed4)

cout << &food << "\n";

// Output the memory address of food with the pointer (0x6dfed4)

cout << ptr << "\n";


3 ways to declare pointer variable

string* mystring; // Preferred

string *mystring;

string * mystring;
Reference operator (&) and Deference
operator (*)
● Reference operator (&) gives the address of a variable.
● Dereference operator (*) we use to get the value stored in the memory address.
● The (*) sign used in the declaration of C++ pointer is not the dereference pointer.
It is just a similar notation that creates a pointer.
Example
#include <iostream>

using namespace std;


int main() {

int *pc, c;
c = 5;
cout << "Address of c (&c): " << &c << endl;

cout << "Value of c (c): " << c << endl << endl;
pc = &c; // Pointer pc holds the memory address of variable c
cout << "Address that pointer pc holds (pc): "<< pc << endl;
cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;

c = 11; // The content inside memory address &c is changed from 5 to 11.

cout << "Address pointer pc holds (pc): " << pc << endl;
cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;

c = 11; // The content inside memory address &c is changed from 5 to 11.

cout << "Address pointer pc holds (pc): " << pc << endl;

cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;

*pc = 2;

cout << "Address of c (&c): " << &c << endl;

cout << "Value of c (c): " << c << endl << endl;

return 0;

}
Output

Address of c (&c): 0x7fff5fbff80c

Value of c (c): 5

Address that pointer pc holds (pc): 0x7fff5fbff80c

Content of the address pointer pc holds (*pc): 5

Address pointer pc holds (pc): 0x7fff5fbff80c

Content of the address pointer pc holds (*pc): 11

Address of c (&c): 0x7fff5fbff80c

Value of c (c): 2
Explanation of the example
● When c = 5; the value 5 is stored in the address of variable c - 0x7fff5fbff8c.
● When pc = &c; the pointer pc holds the address of c - 0x7fff5fbff8c, and the
expression (dereference operator) *pc outputs the value stored in that address,
5.
● When c = 11; since the address pointer pc holds is the same as c - 0x7fff5fbff8c,
change in the value of c is also reflected when the expression *pc is executed,
which now outputs 11.
● When *pc = 2; it changes the content of the address stored by pc - 0x7fff5fbff8c.
This is changed from 11 to 2. So, when we print the value of c, the value is 2 as
well.
There are 3 ways to pass C++ arguments to a
function:

● call-by-value
● call-by-reference with pointer argument
● call-by-reference with reference argument
In C++, by default arguments are passed by value and the changes made in
the called function will not reflect in the passed variable. The changes are
made into a clone made by the called function.

If wish to modify the original copy directly (especially in passing huge object
or array) and/or avoid the overhead of cloning, we use pass-by-reference.
Pass-by-Reference with Reference Arguments does not require any clumsy
syntax for referencing and dereferencing.
Pointer Expressions and Pointer Arithmetic

A limited set of arithmetic operations can be performed on pointers which are:

● incremented ( ++ )
● decremented ( — )
● an integer may be added to a pointer ( + or += )
● an integer may be subtracted from a pointer ( – or -= )
● difference between two pointers (p1-p2)
Pointers to pointers
In C++, we can create a pointer to a pointer that in turn may point to data or other pointer. The syntax

simply requires the unary operator (*) for each level of indirection while declaring the pointer.

char a;

char *b;

char ** c;

a = ’g’;

b = &a;

c = &b;

Here b points to a char that stores ‘g’ and c points to the pointer b.
Void Pointers

This is a special type of pointer available in C++ which represents absence of type.
void pointers are pointers that point to a value that has no type (and thus also an
undetermined length and undetermined dereferencing properties).

This means that void pointers have great flexibility as it can point to any data type.
There is payoff for this flexibility. These pointers cannot be directly dereferenced. They
have to be first transformed into some other pointer type that points to a concrete data
type before being dereferenced.
Invalid pointers

A pointer should point to a valid address but not necessarily to valid elements (like for arrays). These
are called invalid pointers. Uninitialized pointers are also invalid pointers.

int *ptr1;

int arr[10];

int *ptr2 = arr+20;

Here, ptr1 is uninitialized so it becomes an invalid pointer and ptr2 is out of bounds of arr so it also
becomes an invalid pointer.

(Note: invalid pointers do not necessarily raise compile errors)


Null pointers

Null pointer is a pointer which point nowhere and not just an invalid address.

Following are 2 methods to assign a pointer as NULL;

int *ptr1 = 0;

int *ptr2 = NULL;


Uses of pointers

1. To pass arguments by reference


2. For accessing array elements
3. To return multiple values
4. Dynamic memory allocation
5. To implement data structures
6. To do system level programming where memory addresses are useful
Features of pointers

● Pointers save memory space.


● Execution time with pointers is faster because data are manipulated with the
address, that is, direct access to
memory location.
● Memory is accessed efficiently with the pointers. The pointer assigns and
releases the memory as well. Hence it can be said the Memory of pointers is
dynamically allocated.
● Pointers are used with data structures. They are useful for representing two-
dimensional and multi-dimensional
arrays.
Features of pointers

● An array, of any type can be accessed with the help of pointers, without
considering its subscript range.
● Pointers are used for file handling.
● Pointers are used to allocate memory dynamically.
● In C++, a pointer declared to a base class could access the object of a
derived class. However, a pointer to a derived class cannot access the
object of a base class.
Pointer and arrays
While handling arrays with pointers you need to take care few things. First and very
important point to note regarding arrays is that the array name alone represents the
base address of array so while assigning the address of array to pointer don’t use
ampersand sign(&).

Correct: Because arr represent the address of array.

p = arr;

Incorrect:

p = &arr;
Traversing the array using pointers
#include <iostream>

using namespace std;

int main(){

//Pointer declaration

int *p;

//Array declaration

int arr[]={1, 2, 3, 4, 5, 6};

//Assignment

p = arr;
for(int i=0; i<6;i++){

cout<<*p<<endl;

//++ moves the pointer to next int position

p++;

return 0;

}
Output:

6
How to increment pointer’s address and
value?
When we are accessing the value of a variable through pointer, sometimes we
just need to increment or decrement the value of variable though it or we may
need to move the pointer to next int position(just like we did above while working
with arrays). The ++ operator is used for this purpose. One of the example of ++
operator we have seen above where we traversed the array using pointer by
incrementing the pointer value using ++ operator.
// Pointer moves to the next int position (as if it was an array)

p++;

// Pointer moves to the next int position (as if it was an array)

++p;

/* All the following three cases are same they increment the value

* of variable that the pointer p points.

*/

++*p;

++(*p);

++*(p);
Thank you!

You might also like