4 Pointers
4 Pointers
#include <iostream>
using namespace std;
int main()
{
void *p = NULL; //void pointer
cout<<"The size of pointer is:\n“<<sizeof(p);
return 0;
}
Output:
The size of pointer is:4
• Wild pointer: A pointer is said to be a wild pointer if it is not being initialized to
anything. These types of C pointers are not efficient because they may point to
some unknown memory location which may cause problems in our program and
it may lead to crashing of the program.
• Dangling pointer: A pointer pointing to a memory location that has been deleted
(or freed) is called dangling pointer.
There are three different ways where Pointer acts as dangling pointer:
1) De-allocation of memory: deallocate the memory to which pointer is
pointing
2) Variable goes out of scope: data type of pointer and variable is different
3) Function call: pointer is pointing to local variable and if value of variable
changed after function call then the pointer will become dangling pointer
Pointers arithmetic
• There are only a few operations that are allowed to perform on pointers,
these are:
1.Increment/Decrement of a Pointer
2.Addition of integer to a pointer
3.Subtraction of integer to a pointer
4.Subtracting two pointers of the same type
Increment operation
• If we increment a pointer by 1, the pointer will start pointing to the immediate
next location. This is somewhat different from the general arithmetic since the
value of the pointer will get increased by the size of the data type to which the
pointer is pointing.
• new_address= current_address + i * size_of(data type)
Where i is the number by which the pointer get increased.
• For Example: If an integer pointer that stores address 1000 is incremented, then
it will increment by 2(size of an int) and the new address it will points to 1002.
While if a float type pointer is incremented then it will increment by 4(size of a
float) and the new address will be 1004.
Decrement operation