Pointer in C++
Pointer in C++
Pointer in C++
Lecture No. 3
C/C++ Pointers
Pointer Variable Declarations and Initialization
C
… 7 3 4 …
172 173 174 175 176 177 178 179 180 181
C is a variable Memory
P
P is a Pointer ? … 174 3 4 …
832 833 834 835 836 837 838 839 840 841
Pointers
• The statement
P = &C
& ;
int C;
int *P; /* Declare P as a pointer to int */
C = 7;
P = &C;
C
… 7 3 4 …
172 173 174 175 176 177 178 179 180 181
P
… 174 3 4 …
832 833 834 835 836 837 838 839 840 841
Dereferencing
• Applied on pointers
• Access the value of object the pointer points to
• The statement
*P = 5;
puts in C (the variable pointed by P) the value 5
Dereferencing
C
… 7 3
177 4 …
172 173 174 175 176 177 178 179 180 181
P
… 174 3
177 4 …
832 833 834 835 836 837 838 839 840 841
Null Pointer
• A pointer initialized to a o or Null points to
nothing is called Null pointer
• Zero of Null is the only value which can be
initialized to pointer without casting.
• e.g.
• int *p=0;
or
• int *p;
p=0;
Bits and Bytes
0 1 2 3 4 5 6
Storing Variables
. We can either:
– make it point to something that already exists,
• ptr1 = &C ptr = NULL
– or
– allocate room in memory for something new that it
will point to… (dynamic memory will discuss later)
Memory
Pointers & Allocation (2/2)
ptr
? var1 ?
5 var2 ?
5
More C/C++ Pointer Dangers
• Declaring a pointer just allocates space to hold the pointer – it
does not allocate something to be pointed to! Thus the address is
NULL.
void f()
{
int *ptr;
*ptr = 5;
}
Arithmetic on Pointers
• A pointer may be incremented or decremented.
• Example (4)
Memory width is 2 bytes
– int *ptr;
– int num1 = 0;
– ptr = &num1;
– ptr++; 1002 + 4 = 1006
Arithmetic on Pointers
• Example (5) Address data
void main (void) 1000
{
1002 num1 = 93
int *pointer1, *pointer2;
int num1 = 93; 1004
pointer1 = &num1; //address of num1 1006 pointer1 = 1002
pointer2 = pointer1; // pointer1
address is assign to pointer2 1008 pointer2 = 1002
}
Logical operators on Pointers
• We can apply logical operators (<, >, <=, >=, ==, != ) on
pointers.
– But remember pointers can be compared to pointers or
– NULL
• Example (6)
– int *pointer1, *pointer2; // both pointer2 contains NULL
addresses
– int num1 = 93;
– If ( pointer1 == NULL ) // pointer compared to NULL
– pointer1 = &num1;
– pointer2 = &num1;
– If ( pointer1 == pointer2 ) // pointer compared to pointer
• printf(“Both pointers are equal”);