You are on page 1of 14

Lecture 02: Pointers

109104 – Object Oriented Programming (OOP)

Engr. Muhammad Asad

Lecturer (EE)
Institute of Space Technology, Islamabad
muhammad.asad@ist.edu.pk
What are Pointers?
• Variables that store addresses as their values.
• Variable name is direct reference to value.
• Pointer is indirect reference.
• Referencing via pointer is called indirection.
• Enables pass-by-reference.
• Used to create and manipulate dynamic data structures like linked
lists, queue etc.
Count

CountPtr Count

7
Declaration
• int *CountPtr;
• CountPtr is pointer to int
• Char *Ptr;
• Ptr is pointer to char.
Initialization
• Initialized to null
• int *CountPtr=NULL; or int *CountPtr=0;
• Known as null pointer
• Points to nothing
• 0 is the only integer that can be directly assigned to pointer
Pointer Operators
• Address operator (&)- obtains memory address of its operand (unary
operator).
• Indirection Operator (*)- represents a value to which the pointer
operand points(unary operator).
• int y=5;
• Int *yPtr=NULL; // declaring a null pointer

• yPtr=&y; // storing y’s address in yPtr;

• *yPtr=9;

• cin>> *yPtr;

• Cout<< *yPtr; Dereferencing a pointer

• Dereferencing a pointer means accessing the value stored in the location that
the pointer is pointing to.
Pass-by-Reference with Pointers
• Pass-by-Value: modify original values of the arguments in the caller
function.
• Pass- by-Reference: doesn’t actually pass anything. Pointer to
variable is passed by value and copied into function’s corresponding
parameter.
Passing Arrays to Functions
• Value of array’s name is also its address.
• Don’t need to use & operator
• Array name and size specified in function parameters.
• int sum(const int array[], int size)

• int sumPtr(const int *array, int size)


Const Pointers
• Const Informs Compiler that a particular variable’s value shouldn’t be
modified.

• The value shouldn’t be changed in the body of a function.


• Specifies level of access granted.
• Non Constant Pointer to Non Constant Data – Highest access
granted,data cane be modified easily.

• Non Constant Pointer to Constant Data – pointer can point to any


data but the data to which it points cant be modified.

• Constant Pointer to Non Constant Data – Pointer always points to


the same memory location but the data at that location can be
modified.

• Constant Pointer to Constant Data – Minimum access, Pointer


Points to the same location and data cant be modified using that
pointer

You might also like