You are on page 1of 63

UNIT – III

Pointers: Definition and declaration and initialization of pointers.


Accessing values using pointers. Accessing array elements using
pointers.
Functions: Definition and declaration. Built-in functions and User-
defined functions. Categories of functions with example. Pointers
as function arguments, array as function argument, Call-by-value
and call-by-reference. Recursion.
C Pointers

What is a Pointer in C?
• A pointer is defined as a derived data type that can
store the address of other C variables or a memory
location. We can access and manipulate the data
stored in that memory location using pointers.
• As the pointers in C store the memory addresses,
their size is independent of the type of data they are
pointing to.
• This size of pointers in C only depends on the system
architecture.
Syntax of C Pointers
• The syntax of pointers is similar to the variable
declaration in C, but we use the ( * ) dereferencing
operator in the pointer declaration.
datatype * ptr;
where
• ptr is the name of the pointer.
• datatype is the type of data it is pointing to.
• The above syntax is used to define a pointer to a
variable. We can also define pointers to functions,
structures, etc.
How to Use Pointers?
The use of pointers in C can be divided into three steps:
• Pointer Declaration
• Pointer Initialization
• Pointer Dereferencing
1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not
initialize it. To declare a pointer, we use the ( * ) dereference
operator before its name.

• Example
int *ptr;

• The pointer declared here will point to some random memory


address as it is not initialized. Such pointers are called wild
pointers.
2. Pointer Initialization
• Pointer initialization is the process where we assign some initial value to
the pointer variable. We generally use the ( & ) addressof operator to get
the memory address of a variable and then store it in the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;

• We can also declare and initialize the pointer in a single step. This method
is called pointer definition as the pointer is declared and initialized at the
same time.
Example
int *ptr = &var;

• Note: It is recommended that the pointers should always be initialized to


some value before starting using it. Otherwise, it may lead to number of
errors.
3. Pointer Dereferencing
• Dereferencing a pointer is the process of accessing the value
stored in the memory address specified in the pointer. We use
the same ( * ) dereferencing operator that we used in the
pointer declaration.
Dereference
• In the previous example , we used the pointer variable to get the memory
address of a variable (used together with the & reference operator).
• You can also get the value of the variable the pointer points to, by using
the * operator (the dereference operator):
Variables, addresses

int a, b; Memory Value Variable at this


Address address
int *p1, *p2;
0x1000
a = 11; 0x1004 11 a

b = 20; 0x1008 20 b
0x100C
p1 = &a; 0x1010

p2 = &b; 0x1014 0x1004 p1


0x1018 0x1008 p2
0x101C
Declaring a string constant using pointers

char *s1 = “HELLO”;

In the above case, ‘s1’ is a pointer variable that points to a


character. In the above statement, the compiler will allocate space for
the string “HELLO”, and copy the starting address of this space into the
variable ‘s1’.
Address 0x100 0x101 0x102 0x103 0x104 0x105

Contents ‘H’ ‘E’ ‘L’ ‘L’ ‘O’ ‘\0’

Variable s1

Address 0x120

Contents 0x100
C Pointers and Arrays
Pointers & Arrays
• You can also use pointers to access arrays.
• Consider the following array of integers:
Example
int myNumbers[4] = {25, 50, 75, 100};
• You learned from the arrays chapter that you can loop through the array elements
with a for loop:
• Instead of printing the value of each array element, let's print the
memory address of each array element:

• Note that the last number of each of the elements' memory


address is different, with an addition of 4.
• It is because the size of an int type is typically 4 bytes, remember:
So from the "memory address example" above, you can see that the compiler
reserves 4 bytes of memory for each array element, which means that the
entire array takes up 16 bytes (4 * 4) of memory storage:
How Are Pointers Related to Arrays
• In C, the name of an array, is actually a pointer to the first element of the array.
• Confused? Let's try to understand this better, and use our "memory address
example" above again.
• The memory address of the first element is the same as the name of the array:
• This basically means that we can work with arrays through
pointers!
• How? Since myNumbers is a pointer to the first element in
myNumbers, you can use the * operator to access it:
• To access the rest of the elements in myNumbers, you can
increment the pointer/array (+1, +2, etc):
• Or loop through it:
It is also possible to change the value of array elements with
pointers:
Printing the one dimensional array
elements via pointers
Alternate way to use pointer to access array
elements

int arr[10]; /* Declare array ‘arr’ of 10 integers */


int *pa; /* Declare ‘pa’ to be a pointer to a integer */

pa = arr; /* This initializes pointer ‘pa’ to point to the first element of array
‘arr’ – The name of an array evaluates to the starting address of the array */
To access the ‘i’th element of array arr, we can use the following syntax:
int b;
b = pa[i]; /* The pointer variable can be used like the array name */

pa[i] is same as *(pa+i)


Accessing the elements of the two dimensional array
via a simple pointer

In the following code we are printing the


content of the num array using for loop
and by incrementing the value of ptr.

The two dimensional array num will be


saved as a continuous block
in the memory.
So, if we increment the value of ptr by 1
we will move to the next block in the
allocated memory.
2D Arrays and Pointers
int arr1[3][5] = {{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15}};
int (*p2)[5]; /* Declares p2 to be a pointer to an array
of 5 integers */
p2 = arr1[0]; /* Giving only one dimension of ‘arr’
evaluates to the address of the first row of array ‘arr’ */

printf("arr1[0][0]=%d\n",p2[0][0]); printf("arr1[2][3]=
%d\n",p2[2][3]);
Another way to declare 2D pointers

int arr1[3][5] = {{1,2,3,4,5},


{6,7,8,9,10},
{11,12,13,14,15}};

int (*p2)[3][5]; /* Declares p2 to be a pointer to a 2D array of 3 x 5 integers */

p2 = arr1; /* Or, p2 = &arr1[0][0] */

printf("arr1[0][0]=%d\n",(*p2)[0][0]);
printf("arr1[2][3]=%d\n",(*p2)[2][3]);
printf("arr1[1][4]=%d\n",(*p2)[1][4]);
Pointer Arithmetic in C

The C pointer arithmetic operations are slightly different


from the ones that we generally use for mathematical
calculations.

These operations are:


 Increment/Decrement of a Pointer
 Addition of integer to a pointer
 Subtraction of integer to a pointer
 Subtracting two pointers of the same type
 Comparison of pointers
Advantages of Pointers are :-
• Pointer provide direct access to the memory.
• Pointer provides a way to return more than one value to the functions
– Multiple parameters can be declared as pointers through which
values are returned.
• Pointers provides an alternate way to access array elements.
• Used to write system software and low level code – Pointers are used
to address devices in the system.
Disadvantages of Pointers are :-
• Pointer are slower than normal variables.
• Uninitialized pointer can cause segmentation fault when it is
dereferenced.
• If a pointer is accidentally assigned an address that points to another
variable in the program, it can lead to corruption of data when we
write using the pointer.
• Basically, pointer bugs are difficult to handle. So, use pointer effectively
and correctly.
C Functions

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


called.
• A function in C is a set of statements that when called
perform some specific task.
• 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.
• They are also called subroutines or procedures in other
languages.
More on functions
• A C program is nothing but a collection of functions and variables.
• Every C program has at least one function which is called the ‘main’
function.
• All C program’s execution always starts in the ‘main’ function.
• To execute the code in a given function, we ‘call’ that function. This
causes the code in that function to execute. After the function’s code
gets executed, the control returns back to the next statement (after
the function call).
• When we design a program of reasonable complexity, we try to
break down the functionality in to manageable size code blocks that
can be mapped to C functions.
• Functions can take some parameters which are used as part of
achieving the functionality or it can have no parameters as well
Predefined Functions

• You already know what a function is. You have


been using it the whole time while writing
programs.
• For example, main() is a function, which is
used to execute code, and printf() is a
function; used to output/print text to the
screen:
Syntax of Functions in C
The syntax of function can be divided into 3
aspects:
• Function Declaration
• Function Definition
• Function Calls
Function Declarations
• In a function declaration, we must provide the function name, its return
type, and the number and type of its parameters. A function declaration
tells the compiler that there is a function with the given name defined
Syntax

return_type name_of_the_function (parameter_1, parameter_2);

• The parameter name is not mandatory while declaring functions. We can


also declare the function without using the name of the data variables.
Example
• int sum(int a, int b);
• int sum(int , int);

Note: A function in C must always be declared


globally before calling it.
Function Definition
• The function definition consists of actual statements which
are executed when the function is called (i.e. when the
program control comes to the function).
C Function Declaration and Definition

 For code optimization, it is recommended to separate the declaration and


the definition of the function.
 You will often see C programs that have function declaration above main(), and function
definition below main().
 This will make the code better organized and easier to read:
Function Call

• A function call is a statement that instructs the compiler to execute the


function. We use the function name and parameters in the function call.

Note: Function call is neccessary to bring the program control to the function definition. If
not called, the function statements will not be executed.
Create a Function

• To create (often referred to as declare) your own function,


specify the name of the function, followed by
parentheses () and curly brackets {}:

• myFunction() is the name of the function


• void means that the function does not have a return value.
You will learn more about return values later in the next topics
• Inside the function (the body), add code that defines what the
function should do
Call a Function

• Declared functions are not executed immediately. They are "saved for
later use", and will be executed when they are called.
• To call a function, write the function's name followed by two
parentheses () and a semicolon ;
• In the following example, myFunction() is used to print a text (the action),
when it is called:
A function can be called multiple times:
C Function Parameters
Parameters and Arguments
• Information can be passed to functions as a parameter. Parameters act as variables inside the
function.
• Parameters are specified after the function name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma:
• A parameter is a variable that we use in a function definition. (Formal parameters)
• An argument is the actual data that we pass to the function parameter.(Actual Paramaters)

The following function that takes a


string of characters with name as parameter.
When the function is called, we pass along a
name, which is used inside the function to
print "Hello" and the name of each person.
Multiple Parameters

• Inside the function, you can add as many parameters as you


want:
Pass Arrays as Function Parameters

• You can also pass arrays to a function:


Passing arrays as function parameters

When we want to pass an array to a function, it is always passed by giving the name of the array, which is nothing but the
start address of the array.

int slen(char s[])


{
int i=0,len=0;
while(s[i++] != '\0') {
len++;
}
return(len);
}
int main()
{
char s1[]="hello123";
int len;
len = slen(s1); /* Specify the name of the array as the argument to slen() */
printf("len=%d\n",len);
}
Equivalence between array and pointer

int slen(char *s) /* Declaring the format parameter as a char pointer */


{
int i=0,len=0;
while(*s++ != '\0') {
len++;
}
return(len);
}
int main()
{
char s1[]="hello123";
int len;
len = slen(s1); /* Specify the name of the array as the argument to slen() */
printf("len=%d\n",len);
}
Return Values
• The void keyword, used in the previous examples, indicates that the
function should not return a value.
• If you want the function to return a value, you can use a data type (such
as int or float, etc.) instead of void, and use the return keyword inside the
function:

This example returns the sum of a function


with two parameters:
• You can also store the result in a variable:
Function categories

• There are 4 types of functions:


1. Functions with arguments and return values
2. Functions with arguments and without
return values
3. Functions without arguments and with
return values
4. Functions without arguments and without
return values
Pointers as function arguments

• Passing the pointers to the function means the memory location of the variables is passed to
the parameters in the function, and then the operations are performed.
• The function definition accepts these addresses using pointers, addresses are stored using
pointers.
Arguments Passing without pointer
• When we pass arguments without pointers the changes made by the function would be done
to the local variables of the function.
Arguments Passing with pointers

• A pointer to a function is passed in this example. As an argument, a pointer is


passed instead of a variable and its address is passed instead of its value.
• As a result, any change made by the function using the pointer is permanently
stored at the address of the passed variable.
• In C, this is referred to as call by reference.
Difference between the Call by Value and Call by Reference
Call By Value Call By Reference
While calling a function, instead of passing the
While calling a function, we pass the values of values of variables, we pass the address of
variables to it. Such functions are known as “Call variables(location of variables) to the function
By Values”. known as “Call By References.

The value of each variable in the calling function The address of actual variables in the calling
is copied into corresponding dummy variables of function is copied into the dummy variables of
the called function. the called function.

The changes made to the dummy variables in the Using addresses we would have access to the
called function have no effect on the values of actual variables and hence we would be able to
actual variables in the calling function. manipulate them.

In call-by-values, we cannot alter the values of In call by reference, we can alter the values of
actual variables through function calls. variables through function calls.

Values of variables are passed by the Simple Pointer variables are necessary to define to store
technique. the address values of variables.

This method is preferred when we have to pass This method is preferred when we have to pass a
some small values that should not change. large amount of data to the function.
Recursion

• A function that calls itself is known as a recursive function. And, this


technique is known as recursion.
• The recursion continues until some condition is met to prevent it.
• To prevent infinite recursion, if...else statement (or similar approach) can
be used where one branch makes the recursive call, and other doesn't.

Advantages and Disadvantages of Recursion

Recursion makes program elegant. However, if


performance is vital, use loops instead as
recursion is usually much slower.

That being said, recursion is an important


concept. It is frequently used in
data structure and algorithms.

For example, it is common to use recursion in


problems such as tree traversal.
Calculation of Factorial
• Factorial of ‘n’ is given by
n! = 1*2*3*…….*(n-2)*(n-1)*n.
• This can also be written as:
n! = (1*2*3…….*(n-2)*(n-1)) * n
n! = (n-1)! * n
• Such a description lends itself naturally to a recursive
implementation. Suppose we want to write a function
to calculate factorial of ‘n’ which is the parameter, it
can actually call itself with parameter (n-1), and
multiply the returned value with ‘n’ to get the result.
Factorial – Recursive implementation
int fact(int n)
{
if (n == 1)
return 1;
else
return(n * fact(n-1)); /* Recursive call */
}
int main()
{
int x;
scanf(“%d”,&x);
printf(“Factorial of %d = %d \n”,x,fact(x));
}
END OF UNIT-3

You might also like