You are on page 1of 14

Lecture#8

BY

SOBIA SHER

LECTURE AT CSIT

DEPARMENT OF MUST
Pointers LECTURE#8
Passing Arguments to Functions by Reference

 There are two ways to pass arguments to a function


 pass-by-value and
 pass-by-reference
 All arguments in C are passed by value.
 Many functions require the capability to pass a pointer to a large data object to avoid the
overhead of passing the object by value (which incurs the time and memory overheads of
making a copy of the object).
 In C, you use pointers and the indirection operator to simulate pass-by-reference.
Pass-By-Value
Pass-By-Reference
C++ Null Pointers

 It is always a good practice to assign the pointer NULL to a


pointer variable in case you do not have exact address to be
assigned.
 This is done at the time of variable declaration.
 A pointer that is assigned NULL is called a null pointer.
 The NULL pointer is a constant with a value of zero defined
in several standard libraries, including iostream. Consider the
following program −
Pointer to Array

 Pointers are the variables that hold address. Not only can pointers store address of a single
variable, it can also store address of cells of an array..
C++ Pointers and Arrays
C++ Program to display address of array
elements using pointer notation.
value stored in the pointer ptr + 1 using *(ptr + 1)
Pointer Expressions and Pointer Arithmetic

 Pointers are valid operands in arithmetic expressions, assignment expressions and


comparison expressions.
 However, not all the operators normally used in these expressions are valid in conjunction
with pointer variables.
 A limited set of arithmetic operations may be performed on pointers.
 A pointer may be incremented (++) or decremented (--), an integer may be added to a
pointer (+ or +=), an integer may be subtracted from a pointer (- or -=) and one pointer
may be subtracted from another—this last operation is meaningful only when both
pointers point to elements of the same array.
 A pointer can be assigned to another pointer if both have the same type.
Incrementing a Pointer
Decrementing a Pointer
Pointer Comparisons
 Pointers may be compared by using
relational operators, such as ==, <,
and >.
 If p1 and p2 point to variables that are
related to each other, such as elements
of the same array, then p1 and p2 can
be meaningfully compared.

You might also like