Pointers in CPP
Pointers in CPP
Topperworld.in
Pointers
Syntax:
datatype *var_name;
int *ptr; // ptr can point to an address which holds int data
©Topperworld
C++ Programming
Since the data type knows how many bytes the information is held in, we
associate it with a reference. The size of the data type to which a pointer points
is added when we increment a pointer.
❖ Usage of pointer
There are many usage of pointers in C++ language.
An array name contains the address of the first element of the array
which acts like a constant pointer. It means, the address stored in the
array name can’t be changed.
©Topperworld
C++ Programming
For example, if we have an array named val then val and &val[0] can be used
interchangeably.
Example:
#include <iostream>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int* ptr = arr; // Array name 'arr' is treated as a pointer to its first
element
Output:
First element: 10
Second element: 20
©Topperworld
C++ Programming
❖ Pointers to pointers
©Topperworld
C++ Programming
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
©Topperworld
C++ Programming
return 0;
}
Output:
❖ 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
©Topperworld
C++ Programming
❖ NULL Pointers
A null pointer is a pointer that point nowhere and not just an invalid address.
Following are 2 methods to assign a pointer as NULL;
int *ptr1 = 0;
int *ptr2 = NULL;
❖ Advantages of Pointers
⚫ Pointers reduce the code and improve performance. They are used to
retrieve strings, trees, arrays, structures, and functions.
⚫ Pointers allow us to return multiple values from functions.
⚫ In addition to this, pointers allow us to access a memory location in
the computer’s memory.
©Topperworld