Pointers
Pointer is a variable that holds a memory address of another variable.
Pointer declaration:
Syntax:
Dataype
*variable_name;
Data_type
– any valid data type supported by C++.
variable_name
– name of pointer variable.
*
indicates that it is a pointer variable
Pointer Initialization:
ptr=#
The
‘&’ is the address operator, and it represents the address of the variable.
In the
above statement ptr is a pointer variable, num is a normal variable. The
address of num variable is stored in pointer variable ptr.
#include<iostream.>
void
main( )
{
int num,*p;
num=5;
p=#
cout<<”value of
num”<<num<<”\naddress of num=”<<p;
}
Pointer operator or Indirection operator:
The
declarator operator (*) is also called as dereference operator or indirection
operator.
Dereference
is the process of accessing and manipulating data stored in the memory location
pointed to by a pointer.
Direct addressing: Accessing
a variable in one step by using the variable name.
Ex:
num5;
Indirect addressing: Accessing
a variable in two steps by first using a pointer that gives the location of the
variable and then accessing the variable using the location.
Ex: int
*p;
*p=5;
Difference between ‘*’ and ‘&’
operator in pointer:
‘*’
dereference operator. ‘&’ address of operator
Used to
declare the pointer variable, used
to get the address of variable.
Used to
access the value to which the pointer
points to.
Pointer Arithmetic and Pointer
Expressions:
C++
supports four arithmetic operations, that can used with pointers, such as
addition (+), subtraction (-), Incrementation (++), decrementation(--).
We can
add integer value to a pointer.
Ex: p=p+5; // p is a pointer
variable
We can
subtract integer value to a pointer.
Ex: p=p-5; // p is a pointer
variable
We can
perform increment and decrement operations on pointer variable.
Ex: p++;
p--;
We cannot perform multiplication
and division operations on pointers.
Advantages of pointers:
· Pointers
save memory space
· Execution
time with pointer is faster
· It
supports dynamic allocation and de allocation of memory blocks
· It
allows passing variables, arrays, functions etc. as function arguments
· Used to
create and manipulate complex data structures.
Comments
Post a Comment