0% found this document useful (0 votes)
72 views72 pages

Module 3

Uploaded by

Rakshi Suri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views72 pages

Module 3

Uploaded by

Rakshi Suri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 72

Introduction

• Pointer is a derived data type in C.


• It is implemented from one of the
fundamental data types available in c.
• Pointer contain memory address as their
value.
• Since these memory address are the location
in the computer memory where program
instruction and data are stored,

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 1
• Pointers can be used to access and manipulate
the data stored in the memory.
• Pointers provide direct access to
memory.
• Pointers provide a way to return more
than one value to the functions.
• Reduces the storage space and
complexity of the program

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 2
• Pointers allows us to resize the dynamically allocated
memory block.
• Addresses of objects can be extracted using pointers
• Reduces the execution time of the program
• Provides an alternate way to access array elements
• Pointers can be used to pass information back and
forth between the calling function and called
function.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 3
• Pointers allows us to perform dynamic
memory allocation and deallocation.
• Pointers helps us to build complex data
structures like linked list, stack, queues,
trees, graphs etc.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 4
• Example:
• Int quantity=100;
• Now the variable stores the value
somewhere in the memory.
• Let us assume that 5000 is the address for
quantity.
• We can access 100 by either the name
quantity or by the address 5000.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 5
Since memory address are numbers, they can
be assigned to some variables, that can be
stored in memory, like any other variable.
Such variable that hold memory address are
called pointer variable.
•Pointer is nothing but variable that contains
an address, which is a location of another
variable in memory.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 6
• There are three underlying concepts
1. Pointer constant
2. Pointer value
3. Pointer variable

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 7
• Pointer constant
Memory address within a computer are referred to as pointer constant.
We can’t change them ;we can only use them to store data values.
We can’t save the value of memory address. we can get the value through the
variable stored there using the address operator(&).
• Pointer value
Pointer value may change from one run of the program to another.
Once we have a pointer value, it can be stored in another variable.
• Pointer variable
The variable that contains pointer value is called pointer varibles

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 8
Accessing the address of a variable

• We can determine the address of a variable using the help


of operator &.
• For example:

• The & operator can be used only with the simple variable or
an array element
• We can’t use like this:

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 9
• If x is an array, then expressions such as

• It is valid and represents the address of 0th and (i+3)th


elements of x.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 10
Example code

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 11
Declaring pointer variable

• Pointer variables contain addresses that belong to a


separate data type, they must be declared as
pointers before we use them.
• Declaration of a pointer variable:

• Eg:

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 12
• We can also declare

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 13
Initialization of a pointer

• The process of assigning the address of a variable to


a pointer variable is known as initializations.
• Once a pointer variable has been declared we can
use the assignment operator to initialize the
variable.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 14
• We can also combine the initialization with the
declaration.

• Another style:

• We can also define a pointer variable with an initial


value NULL and 0.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 15
• Pointers are flexible
• We can make the same pointer points to different data
variables in different statement
• We can also use different pointer points to same
variable.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 16
Accessing a variable through its pointer

• Accesing a value of variable using pointer is done by


* operator. it is usually called as indirection
operator or dereferencing operator

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 17
POINTERS
 So, the pointer variable declaration becomes something like
this,
int   *pTonRate;
 In other word, the pTonRate variable holds the memory
address of nRate and is therefore a pointer to nRate.
 The asterisk (*) is used to show that is it the pointer
variable instead of normal variable.

Definition: A pointer is a variable that holds


memory address of another variable, where, the
actual data is stored.
POINTERS
Pointers and Simple Variables

 A pointer is a numeric variable and like other variables, must be declared


and initialized before it can be used.
 The following is a general form for declaring a pointer variable,

Data_type * pointer_variable_name;

 For example,

char*    chName;
int   *    nTypeOfCar;
float    *fValue;

 type_of_stored_data is any valid pointer base type such as char, int,


float or other valid C derived types such as array and struct.
 It indicates the type of the variable’s data to which the pointer is pointed
to.
 The pointer_variable_name follows the same rules as other C variable
naming convention and must be unique.
POINTERS
 From the pointer declaration examples, in the first line, the
declaration tells us that chName is a pointer to a variable of type
char.
 The asterisk (*) is called indirection operator, and it indicates that
chName is a pointer to type char and not a normal variable of type
char.
 Note the position of the *, it is valid for all the three positions.
 Pointers can be declared along with non pointer variables as shown
below,

// chFirstName and chSecondName both are pointers to


// type char while chInitial is normal char type variable
char    *chFirstName, *chSecondName, chInitial;
// fValue is a pointer to type float, and fPercent
// is an ordinary float type variable.
float    *fValue, fPercent;
POINTERS Initializing Pointers

 Once a pointer is declared, we must initialize it.


 This makes the pointer pointing to something.
 Don’t make it point to nothing; it is dangerous.
 Uninitialized pointers will not cause a compiler error, but using an
uninitialized pointer could result in unpredictable and potentially
disastrous outcomes.
 Until pointer holds an address of a variable, it isn’t useful.
 C uses two pointer operators,
• Indirection operator (*) – asterisk symbol, has been explained
previously.
• Address-of-operator (&) – ampersand symbol, means return
the address of…
 When & operator is placed before the name of a variable, it will
returns the memory address of the variable instead of stored
value.
POINTERS
 Program example: initializing a pointer

 In this example, pointer variable, pToInt receives the


address of nLocation or
 The memory address of the nLocation variable is
assigned to pToInt pointer variable.
POINTERS
 Graphically this situation can be illustrated as shown below.

 The * operator is a complement of & operator.


 * means returns the current value of the variable pointed to.
POINTERS
 From the previous example, if we declare another variable of type int,

int anotherVar;
int    * pToInt;
pToInt = &nLocation;
nLocation = 100;

 Then, statement,

anotherVar = *pToInt;

 will place the actual current data value stored in variable nLocation into
variable anotherVar.
 Which means anotherVar was assigned the actual current data value
stored at the memory address held by pToInt.
 The * operator appears before a pointer variable in only two places:

• When declaring a pointer variable.


• When de-referencing a pointer variable (to show the data it‘s pointed to).
Using Pointers POINTERS
 Only the addition and subtraction operations are permitted in pointer's
expression.
 As with any variable, a pointer may be used on the right hand side of
an assignment statement to assign its value to another pointer as
shown in the following example.
 Program example: using pointers
POINTERS
 The situation can be illustrated as shown below.  The memory address
should be different for different run/system.

 Take note the difference between memory address and the actual data value,
which stored at the memory address.
 Do not worry about the address, which are determined and provided by the
system.
 From the previous example, we can:
1. Access the variable's content by using the variable name (iNum) and is
called direct access.
2. Access the variable's content by using a pointer to the variable
(*iPointerOne or *iPointerTwo) and is called indirect access or
indirection.
POINTERS
 As a conclusion, if a pointer named pPointerVar of type int has
been initialized to point to a variable named iNumVar, the following
are true,

// declare a pointer variable named pPointerVar, where the


// data stored pointed to by pPointerVar is int type
int * pPointerVar;
// assign the iNumVar's address to pPointerVar pointer variable
pPointerVar = &iNumVar;

 * pPointerVar and iNumVar both refer to the contents of


iNumVar (that is, whatever data value stored there).
 pPointerVar and &iNumVar refer to the address of iNumVar (the
pPointerVar only hold the address of variable iNumVar not the
actual data value).
 So, a pointer name without the indirection operator (*) accesses the
pointer value itself, which is of course, the address of the variable
pointed to.
POINTERS
 Program example: using pointers operator

 The address displayed for variable iNormVar may be


different on your system because different computer will
have different specification.
POINTERS
 For pointer arithmetic operation, only two arithmetic operations, that is
addition and subtraction available.  For example,
int    iAge = 35;

 Hence, C reserved storage for the variable iAge and store the value
35 in it.
 Let say, C has stored this value at the memory address 1000, then
we declare a pointer variable named pPointerToAge that point to
the iAge variable.
 Then, after the following expressions have been executed,
int * pPointerToAge;
pPointerToAge = &iAge;
pPointerToAge++;

 The content of the pointer then becomes 1004 instead of 1001


(integer value takes 4 bytes so C add 4 to the pointer).
POINTERS
 Different variable types occupy different amount of memory,
implementation dependent, following C standard or implementation
extension and whether 16, 32 or 64 bits system.
 Each time the pointer is incremented, it points to the next integer and
similarly, when a pointer is decremented, it points to the previous
integer.
 Each individual byte of memory has its own address; so multi-byte
variable actually occupies several addresses.
 When pointers used to handle the addresses of multi-byte variables,
the address of a variable is actually the address of the lowest byte it
occupies.
 For example,

int     iNum = 12252; // 4 bytes


char    chVar = 90; // 1 byte
float   fVar = 1200.156004; // 4 bytes
POINTERS
 The pointer variables are pointing to the lowest byte of
variable memory slots e.g: iNum occupies 4 bytes and
chVar occupies 1 byte.
 Other pointer arithmetic operation is called differencing,
which refers to subtracting two pointers.
 For example, two pointers that point to different elements
of the same array can be subtracted to find out how far
apart they are.
 Pointer arithmetic automatically scales the answer, so
that it refers to the array elements.
 Thus, if pPointer1 and pPointer2 point to elements of
an array (of any type), the following expression tells you
how far apart the elements are,
pPointer1 – pPointer2;
POINTERS
 However ptrdiff_t type can be used to return
the subtraction operation between two pointers.
 It is a base signed integer type of C/C++
language.
 The type's size is chosen so that it could store
the maximum size of a theoretically possible
array of any type.
 On a 32-bit system ptrdiff_t will take 32 bits,
on a 64-bit one 64 bits.
 The ptrdiff_t type enable you to write well-
portable code.
 ptrdiff_t (together with wchar_t and
size_t) defined in stddef.h (cstddef for C++).
05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA
23/51
Pointers Comparison POINTERS
 The comparison is valid only between pointers that point to the
same array.
 The following relational operators work for pointers operation:
==, !=, >, <, >= and <=.
 A lower array element that is those having a smaller subscript,
always have a lower address than the higher array elements.
 Thus if pPointer1 and pPointer2 pointing to the elements
of the same array, the following comparison is TRUE,
pPointer1 < pPointer2
 If pPointer1 points to an earlier member of the array than
pPointer2 does.
 Many arithmetic operations that can be performed with regular
variables, such as multiplication and division, do not work with
pointers and will generate errors in C.
POINTERS
 The following table summarizes pointer operations.

Operation Description
You can assign a value to a pointer.  The value should be
1. Assignment (=) an address with the address-of-operator (&) or from a
pointer constant (array name)
The indirection operator (*) gives the value stored in the
2. Indirection (*)
pointed to location.
You can use the address-of operator to find the address of a
3. Address of (&)
pointer, so you can use pointers to pointers.
You can add an integer to a pointer to point to a different
4. Incrementing
memory location.
You can subtract an integer from a pointer to point to a
5. Differencing
different memory location.
6. Comparison Valid only with two pointers that point to the same array.
POINTERS
Uninitialized Pointers Issue

 Let say we have declared a pointer something like this,

int  *iPtrVar;

 This statement declares a pointer to type int but not yet initialized, so it
doesn’t point to anything known value (address).
 Then, consider the following pointer assignment statement,

// this is not an address that system allocate!


*iPtrVar = 121;
POINTERS
 This statement means the value of 121 is assigned to whatever address
(00??????) iPtrVar is pointing to.
 That address can be anywhere in memory which may contain critical data.
 The 121 stored in that location may overwrite some important information,
and the result can be anything from program error to a full system crash.
 We must initialize a pointer so that it point to something.  Do not create a
stray pointer.
 A better solution, we can assign NULL (\0) value during the initialization
before using it, such as,
int  *iPtrVar = NULL; /* null pointer, pointing to something
but nothing */

 For pointer that point to a string you may just point to an empty string for a
dummy such as,

char    *chMyString = " ";


 The .NET C/C++ programming uses nullptr instead of NULL. The
 NULL/nullptr is a pointer that point to the 0x00000000 (32 bits system)
memory address.

www.tenouk.com, ©
Pointers to Pointers
POINTERS
 Graphically, the construct of a pointer to pointer
can be illustrated as shown below.
 iPointerOne is the first pointer, pointing to the
second pointer, iPointerTwo and finally
iPointerTwo is pointing to a normal variable
iNum that hold integer 100.

www.tenouk.com, ©
Advantages
Functions

• A function is a block of code which only runs when it is


called.
• You can pass data, known as parameters, into a
function.
• Functions are used to perform certain actions, and they
are important for reusing code: Define the code once,
and use it many times.
• Functions are user-defined function.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 39
• Elements of user defined functions we have
following steps
1.Definition of function.
2.Function call.
3.Declaring function.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 40
1.Function definition

• it is an independent program module that is


written to implement the requirements of the
program.
• Definition of function having block of code
to do specific task.
• It is also called function implementation.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 41
• Having following elements.
1. Function name;
2. Function type;
3. List of parameters;
4. Local variable declaration;
5. Function statements;
6. A return statement;
• All these six elements are grouped into two
parts
• Function header(First three element)
• Function body(second three variable)

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 42
• A general format of a function definition to
implement these two parts:

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 43
• The first line function_type
function_name(parameter list) is known as
the function header and the statements within
the opening and closing braces constitute the
function body.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 44
2. Function Call

• Function call will be written inside the main()


function.
• A function can be called by simply using the
function name followed by a list of actual
parameter.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 45
• When compiler encounters function call, the
control is transferred to the function
definition.
• This function executed line by line and a
value is returned when a return statement is
encountered
• Syntax:
• Example: mul(x,y);

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 46
3. Declaring function

• If we want to use any function in the program


we have to declare that function before using
it.
• We have to declare the function outside the
main()
• It consist four parts:
1. Function type.
2. Function name.
3. Parameter list.
4. Terminating with semicolon.
05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 47
• This is similar to the definition header of the
function.
• Syntax

• Example

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 48
Call by value

• In call by value method, the value of the actual parameters is copied


into the formal parameters. In other words, we can say that the value
of the variable is used in the function call in the call by value method.
• In call by value method, we can not modify the value of the actual
parameter by the formal parameter.
• In call by value, different memory is allocated for actual and formal
parameters since the value of the actual parameter is copied into the
formal parameter.
• The actual parameter is the argument which is used in the function
call whereas formal parameter is the argument which is used in the
function definition.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 49
05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 50
05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 51
Call by reference

• In call by reference, the address of the variable is passed into


the function call as the actual parameter.
• The value of the actual parameters can be modified by
changing the formal parameters since the address of the
actual parameters is passed.
• In call by reference, the memory allocation is similar for both
formal parameters and actual parameters. All the operations
in the function are performed on the value stored at the
address of the actual parameters, and the modified value gets
stored at the same address.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 52
05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 53
05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 54
Pointer as function argument

• Refere call by reference topic.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 55
Recursion

• Recursion is the process which comes into existence


when a function calls a copy of itself to work on a
smaller problem.
• Any function which calls itself is called recursive
function, and such function calls are called recursive
calls.
• Recursion involves several numbers of recursive calls.
However, it is important to impose a termination
condition of recursion.
• Recursion code is shorter than iterative code however it
is difficult to understand.
05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 56
• Recursion cannot be applied to all the problem, but it is more
useful for the tasks that can be defined in terms of similar
subtasks.
• For Example, recursion may be applied to sorting, searching,
and traversal problems.
• Generally, iterative solutions are more efficient than
recursion since function call is always overhead.
• Any problem that can be solved recursively, can also be
solved iteratively.
• However, some problems are best suited to be solved by the
recursion, for example, tower of Hanoi, Fibonacci series,
factorial finding, etc.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 57
To find factorial number

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 58
• How to calculate factorial number.
• n *fact(n-1)
• When we write an recursive functions, we
must have an if statement somewhere to force
the function to return without recursive call
being executed. otherwise function will never
return.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 59
Passing arrays to function

One dimensional array:


we can pass normal variable to the function as
an argument like wise in C we have another
opportunity to pass the array as an argument to
the function.
•For this we have to declare a function :
datatype function_name(datatype [],datatype,
…);

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 60
• After declaration we have to call the fuction
in main() program.In function call we need
not use any subscript as parameter. We are
directly pass the array variable name.
• Syntax: function_name(variable name1,….);

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 61
• After calling the function we have define the function to do
specific task. In the formal parameter we have to use array
name with subscripts and data type.
• Syntax:
• return_type function_name(datatype v_name[],datatype
v_name2….)
{
Code of block;
}

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 62
• Example:

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 63
Two dimensional array

• It is like simple array , we can also pass multi dimensional


arrays to functions.
• The function must be called by passing only the array name.
syntax: function_name(array_name,size_row,col_size);
• In the function definition, we must the array has two
dimensions by including two subscripts.
syntax: return_type function_name(data type
array_name[][col_size],size_row,col_size)
{
------------;
}

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 64
TWO DIMENSIONAL ARRAY

• The size of the second dimensions must be specified.


• The prototype declaration should be similar to the function
header

Syntax:
return_type function_name(data type [][], datatype,
datatype);

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 65
• Example:

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 66
Passing string to function

• The string are treated as character arrays in c.


• The rules for passing strings to functions are similar to those for
passing arrays to function.
• Basic rules:
• The string to be passed must be declared as a formal argument of
the function when it is defined.
Example:
void display(char name[])
{
---------;
}

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 67
Passing string to function

• The function prototype must show that the argument is a


string. for the above definition ,the declaration can be
written as

void display(char []);

• A call to the function must have a string array name without


subscripts as its actual argument.

display(name);

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 68
Example:

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 69
Functions returning pointer

• Function can return single value by its name or return multiple values
through pointer parameters.
• Since pointer is also a datatype in c, we can also force a function to
return a pointer to the calling function.

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 70
• Example:

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 71
Pointer to function

• A function has a type and address location in the memory. It is


therefore, possible to declare apointer to a function, which can then
be used as an argument in another function.
• A pointer to function declared as:
type (* f_ptr)();

05/25/22 Mrs.Rakshithap_Assistant_Proffesor_Dept_MCA 72

You might also like