Вы находитесь на странице: 1из 9

Sruthi M, ECE

Online Lecture 2- EC312 OOP

C++ Pointers

Ref: Object Oriented Programming using C++ and JAVA, E. Balaguruswamy, Mc Graw Hill
Education
Pointers
• It is a derived data type that refers to another
data variable by storing variable’s memory
address rather than data

• A pointer variable defines where to get the


value of a specific data variable instead of
defining actual data
Declaration Format
• data_type *pointer_variable;

• data_type -> int,float,char..etc.


• pointer_variable -> Name of pointer
• * - Asterisk symbol which distinguishes a
pointer variable from other variables
Declaration Example

• int *ptr, a; // Declaration


• ptr = &a; // Initialization

• ‘&’ to retrieve address of a variable


Sample Program 1
• #include <iostream> • // print the address stored
• using namespace std; in ip pointer variable
• int main () • cout << "Address stored in
• { ip variable: ";
• int var = 20; // actual • cout << ip << endl;
variable declaration. • //Access the value at the
• int *ip; // pointer variable address available in pointer
• ip = &var; // store address • cout << "Value of *ip
of var in pointer variable variable: ";
• cout << "Value of var • cout << *ip << endl;
variable: "; • return 0;
• cout << var << endl; • }
Sample Program 1 - Output
• When the above code is compiled and
executed, it produces result as follows −
– Value of var variable: 20
– Address stored in ip variable: 0xbfc601ac (some
hex value)
– Value of *ip variable: 20
Pointer Concepts
1. Null pointer
2. Pointer Arithmetic
3. Using Pointers with arrays and Strings
4. Array of Pointers
5. Pointer to pointer
6. Pointer to function
7. Pointer to Objects
8. This Pointer
9. Pointers to derived class
Null Pointer
• The pointers which are not initialized in a
program or do not have exact address to be
assigned, are called Null pointers.
• The NULL pointer is a constant with a value of
zero defined in several standard libraries,
including iostream
Sample program – Null pointer
• #include <iostream>
• using namespace std;
• int main ()
• {
• int *ptr = NULL;
• cout << "The value of ptr is " << ptr ;
• return 0;
• }

• Output of the above code - The value of ptr is 0

Вам также может понравиться