0% found this document useful (0 votes)
11 views46 pages

Unit - 4 Notes

The document discusses functions and pointers in C programming. It defines what a function is, the different parts of a function like name, parameters, return type, and function blocks. It also covers function declaration, definition, calling and advantages of using functions. The document then discusses pointers, their definition and initialization.

Uploaded by

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

Unit - 4 Notes

The document discusses functions and pointers in C programming. It defines what a function is, the different parts of a function like name, parameters, return type, and function blocks. It also covers function declaration, definition, calling and advantages of using functions. The document then discusses pointers, their definition and initialization.

Uploaded by

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

UNIT IV

FUNCTIONS AND POINTERS

Syllabus:

Function – Definition of Function – Declaration of Function – Pass by Value – Pass by Reference – Recursion –
Pointers – Definition – Initialization – Pointers arithmetic – Pointers and Array – Example Problems.

Introduction:

4. FUNCTIONS AND POINTERS

5.1 Functions – User Defined Functions

Real time examples:

 We have got various functions in our body for doing specific tasks.
o Heart for pumping blood in veins
o Lungs for breathing
o Eyes for vision
o Legs for walking
o Nose for smell
Solutions:
Similarly in programming we need something to handle our repetitive or specific task and they are called
function.
A Function
i accepts some input
ii process it
iii produces output.
Function Concept In Mathematics
f(x) = 5x -3
Where,
f - is an function name
x - is an argument or input of function
5x-3 - is an definition of an function
when x=1
f(1) = 5(1)-3
f(1) = 2
2 is the return value of function
when x=2
f(2) = 5(2)-3
f(2) = 7
7 is the return value of function
So, every function must have name, argument (input) and return (output) type.

Consider another example,

sum(x,y) = x+y.

Where,

sum - is an function name.


x,y - is an argument or input of function.
x+y - is an definition of an function.
When x=2, y=3

sum(2,3) = 2+3.
=5
Here 2,3 are arguments and 5 is the return value.

5.1.1 Introduction to Functions

Introduction to Functions

Functions are a block of statements (called as modules) that perform a specific task assigned by the user.
Functions accept an input, perform a task and produce the output.
Input Function Output

Function reduces the redundancy of code.


It breaks down a large program in small modules to improve readability, portability as well as makes the
program easy to debug.

Functions can be categorized into 2 types

1.Pre-Defined function

2.User Defined function

Pre-Defined Vs User Defined

Pre-Defined Function User Defined function


Pre-Defined functions are Library User defined functions are the
function. function which are created by user as
per their own requirements.
Pre-Defined functions are part of User defined functions
header file. are part of the program which is
(such as math.h) which is called called during compiling.
runtime.
Name of function can't be Name of function can be changed
changed. any time.
The declaration and definition of a User is going to declare and define
function is already known to the that function in the program.
compiler.

5.1.2 Need for Functions

If we want to execute a block of statements again and again repeatedly, then we have to repeat the block of
statements again and again, which will increase the size of program code, but if we place the block of
statements that will be repeated inside the function, then we need not repeat the block of code again and again,
instead we can just call the function again and again.

Consider the example,

2,3 add 5

3,4 add 7

4,5 add 9

5,6 add 11

6,7 add 13

In the above illustration only the input and output is changing, but the function add remains constant.

So we need not write add the function again and again, instead we can write the add function only once and call
it again with different sets of inputs.

2,3 5

3,4 7

4,5 add 9

5,6 11

6,7 13
5.1.3 Advantages of Writing Function

1. Modular and Structural Programming


 We can divide c program in smaller modules.
e.g. A calculator program can be divide into 4 modules such as add,sub,multiply and divide.
 We can call these modules whenever required.
 Modules once created, can be re-used in other programs.

1. Individual functions can be built independently without any amiguity


2. More than one modules can be developed paralelly.
3. Testing can be done effectively, when we test individual modules rather than testing the entire
program
5. Frequently used functions can be put together in the customized library
 frequently used functions can be put in our custom header file and it can be included in other programs
too.

6. A function can call other functions & also itself


 Function can call other function.
 Function can call itself, which is called as “recursive” function.
 Recursive functions are also useful in order to write system functions.

7. It is easier to understand the Program, when a program is divided into small modules
 We can get overall idea of the program by just looking at the function names itself.

5.1.4 Elements of a User Defined Function

5.1.4.1 Function Name

A function name is any variable name that the user gives to the function.

Function naming rule

 Name of function includes only alphabets, digit and underscore.


 First character of name of function must be an alphabet or underscore.
 Name of function cannot be any keyword of c program.
 Name of function cannot be a global identifier(global varaible name).
 two function cannot have same name within the scope.
 Name of function is case sensitive(abc & Abc are two different functions)
5.1.4.2 Arguments / Parameter

Arguments are nothing but the input that has been given to the function.The parameters can be passed to a
function by two different methods.

(a) Pass by value: In this approach only the copy of the actual variables is passed as a input to the function.
Hence any modification done inside the function will not be reflected in the actual variable.

(b) Pass by reference: In this approach the memory address of the actual variables is passed as a parameter to
the function. Hence any modification done inside the function will be reflected in the actual variable.

Note: Argument should have an valid data type.

Parameter: The names given in the function definition are called Parameters.

Argument: The values supplied in the function call are called Arguments.

5.1.4.3 Return Type

The return type is nothing but the output or result obtained after the execution of the functions.

 Using return keyword output can be passed from the function.


 When the program control reaches the return keyword it immediately terminates the execution of that
function and transfers the control to the calling function.
Note: A function can return only one value. Return type should be an valid data type.

5.1.5 Various Blocks of a Function

Any function need to have the following three blocks.

1.Function Declaration – Introducing the function to the compiler

2.Function Definition – defining the role of the function

3.Function Calling – Calling the function

5.1.5.1 Function Declaration


 Declaration of function in C is called as Prototype Declaration.
 Function Declaration is also called as Function Prototype.
Function declaration is similar to a variable declaration. It provides the following information to the Compiler
It should contain three parts.

1. The return type.(the data type of the result/output)


2. The function name
3. The parameter list(the data type of the inputs )

Some Important Point in function declaration:


 Prototype declaration should always end with a semicolon.
 Parameter List is Optional.
 Default Return Type is Integer.
Note: if there are no parameters or return type in a function.you can specify as void
Syntax

ReturnType FunctionName(ArgumentType1, ArgumentType2, ...., ArgumentTypeN);

Example

If you are going to create a function name add, that accepts two integer values as input adds the two values
and gives the result as integer value, then the function declaration would be as follows,

int add(int,int);

Few more examples of function declaration are given below

Function with no argument and integer as return type

int getValue(void);

Function with integer argument and integer as return type

int square(int);

Function with no argument and no return type

void display(void);
Note:

 If function Definition is Written after the main function then only we need Prototype Declaration in
Global Declaration Section
 If function Definition is written before the main function then, we don’t need write Prototype
Declaration
 Function’s declaration doesn’t reserve any memory space.

Example Program

Function Definition Written After Main


#include<stdio.h>
void show(); // Function Declaration
void main()
{
displayMessage();
}
void show()
{
printf("After Main");
}

Function Definition Written Before Main


#include<stdio.h>
void show()
{
printf("Before Main");
}
void main()
{
displayMessage();
}
Here the function Definition is written above the main function so there is no Function Declaration.

More on Function Declaration

If we write Function declaration


1. The Prototype declaration tells compiler that we are going to define this function somewhere in the
program.

2. Compiler will have prior information about function.

3. As the Compiler have prior information, during function calling compiler looks forward in the program
for the function definition.

If we don’t write function declaration then

1. Compiler doesn’t have any reference of Function.

2. Compiler doesn’t have prior information of that function.

3. Compiler gets confused and throws error.

5.1.5.2 Function Definition


It defines what specific task a function should do. This is done by including the block of the statement (that
does a specific task) inside the function.

 Function definition is nothing but body of the Function.


 It contains Executable Code (Executable statements).
 It defines what task a function shoud do.
 First Line of the is called as Function Header.
 Function Header should is identical to function Prototype but
o There is no semicolon at the end.
o It specifies the variable name of the input data type too.

Syntax
ReturnType FunctionName(ArgumenTtype with VariableName)
{
Block of statements;
}
Block of statements may include variable declarations, statements and return value etc.

Note: The return statement forces the function to return immediately eventhough if function is not yet
completed.

Example of function definition

int add(int a,int b)


{
int c;
c=a+b;
return c;
}
Note: In the argument list of function definition, you specify the variable name also. A semi-colon should
not be placed at end of the first line of the function definition.

Another Example:

int add(int a,int b)


{
int c;
return c;
c=a+b;

}
Here the function terminates after reaching the return statement without executing the statement “return c”

Example Program

#include<stdio.h>
int add(int a,int b) //Function Definition
{
return a+b;
}
void main()
{
int x=10,y=20;
int sum;
sum = add(x,y); // Function Calling
printf("\nSum = %d",sum);
}

Output
30

5.1.4.3 Function Calling

 A function calling statement instructs the compiler to execute the function that is being called.
 When a program calls a function, program control is transferred to the called function.

When a function is called, the called function performs the specified task and when the return statement is
executed or when its function-ending closing brace is reached, it returns the program control back to the main
program.

To call a function we need to pass the required parameters along with function name and if the function returns
a value it has to be stored.

Syntax

functionName(argumentValue)
Example 1

add(5,6);

or

add(a,b);

Example 2

a = add(5,6);

or

b = add(a,b);

here a and b are varaibles that will store the values returned by the function add.

Without function calling statement a function will not be executed.

Note: In a function calling statement we need not specify a return value .

An example program using functions

Example Program

#include<stdio.h>
int addition(int,int); // funciton declaration
void main()
{
int x=10,y=20;
int sum;
sum = addition(x,y); // Function Calling
printf("\nSum = %d",sum);
}
int addition(int a,int b) //Function Definition
{
return(a+b);
}

Output
30

5.1.6 Functions Prototype

5.1.6.1 No Argument and No Return Type

It means that no input will be passed to the function and no value will be returned from the function. Everything
happens within the function.

Example

void add(void); // function declaration


void main()
{
add(); // function call
}
void add(void) // function definition
{
int a=10,b=5;
int c;
c=a+b;
printf(“%d”,c);
}

5.1.6.2 With Argument and No Return Type


It means that input will be passed to the function and no value will be returned from the function.

Example:
void add(int,int); //function definition
void main()
{
int a=10,b=5;
add(a,b); // function call
}
void add(int a,int b) // function definition
{
int c;
c=a+b;
printf(“%d”,c);
}

5.1.6.3 No Argument and With Return Type


Here no argument will be passed to the function, but the function will return a value.

Example:

int add(void); // function declaration


void main()
{
int c;
c=add(); // function call
printf(“%d”,&c)
}
int add(void) // function definition
{
int k;
int a=10,b=5;
k=a+b;
return(k)
}

5.1.6.4 With Argument and With Return Type


It means that input will be passed to the function and a value will be returned from the function.
Example:

int add(int,int); // function declaration


void main()
{
int a=10,b=5;
int c;
c=add(a,b); // function call
printf(“%d”,&c)
}
int add(int x,int y) // // function definition
{
int k;
k=x+y;
return(k)
}

5.1.7 Actual Parameter Vs Formal Parameter

Parameter:

A parameter is an expression which is passed to a function by its caller in order for the function to perform its
task. It is an expression in the comma-separated list bound by the parentheses in a function call expression.

Actual Parameter:

Actual parameter is nothing but the arguments of the calling function. It is specified in the function calling
statement.

E.g.:
Actual
parameter
Add(A,B);

Parameter Written In Function Call Is Called “Actual Parameter”.

Formal Parameter

Formal Parameter Is Nothing But The Arguments Of The Called Function. It Is Specified In The Function

Formal
Definition.

E.g.:

int Add(Int A,Int B)

Parameter Written In Function Definition Is Called “Formal Parameter”.

Note: Every Time When A Function Is Called, The Value Of Actual Parameter Gets Assigned To Formal
Parameter.

Example Program

Example:

#include <stdio.h>
void sum(int i, int j, int k);
void main()
{
Int a = 5;
sum(3, 4, a); // actual arguments
}
void sum(int i, int j, int k) // formal arguments
{
int s;
s = i + j + k;
printf("sum is %d", s);
}
Here 3, 4, a are actual arguments and i,j,k are formal arguments.

5.1.8 Pass by Value Vs Pass by Reference


In C Programming we have different ways of parameter passing schemes and they are
1. Pass by Value
2. Pass by Reference
Pass by Value
 In pass by value we pass the value as input
 While Passing Parameters using pass by value, a copy of original parameter is created and passed to the
called function.
 Any update made inside method will not affect the original value of variable in calling function.
Example Program

#include<stdio.h>
void swap(int n1,int n2)
{
int temp;
temp = n1;
n1 = n2;
n2 = temp;
}
void main()
{
int a=50,b=70;
swap(a,b);
printf("\nA = %d",a);
printf("\nB = %d",b);
}
Output
Number 1 = 50
Number 2 = 70
Explanation
In the above example a and b are the actaul values and copy of these values are passed to the function and these
values are copied into n1, n2 variable of sum function respectively. When the values are swapped only n1 and
n2 got interchanged,whereas a and b remained unalterd.

Pass by Reference/Pointer/Address
 Pass by reference we pass the memory address of the variable as input.
 While passing parameter using pass by address scheme, we are passing the actual address of the
variable to the called function.
 Any updates made inside the called function will modify the original copy since we are
directly modifying the content in the memory location itself.
Example Program

#include<stdio.h>

void swap(int *n1,int *n2)


{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
void main()
{
int a=50,b=70;
swap(&a,&b);
printf("\nA = %d",a);
printf("\nB = %d",b);
}
Output
A = 70
B = 50

Explanation
In the above example a and b are the actual values and the memory addresses of these values are passed to the
function and when the values are swapped, the values in the memory address got interchanged, and the values a
and b have got swapped.

Note: we have used * to denote pointer variables which are capable of holding memory addresses. We have
used & to obtain the address instead of value.(you will better understand this in the section)

Difference between Pass by Value and Pass by Reference

Pass by Value Pass by Reference


Creates a new memory location for formal
Passes only a pointer to the memory location
parameters
Duplicate Copy of Original Parameter is
Actual Copy of Original Parameter is Passed
Passed
No effect on Original Parameter after Original Parameter gets affected if value of
modifying parameter inside the function parameter changed inside function

Note: Pass by Reference is particularly useful when we return more than one values form the function.

5.1.9 Nested Functions


Nested function is nothing but a function inside another function.

If we are calling any function inside another function call is known as nested function call.

Example 1

Consider there are two functions add() and squre()

Function add() Function square()


int add(int a,int b) int square(int a)
{ {
int sum; int sqr;
sum=square(a)+square(b); sqr=a*a;
return sum; return sqr;
} }

The function square( ) is inside the function sum( ) and so the function sum( ) is nested function

Function add()
int add(int a,int b)
{
int sum;
sum=square(a)+square(b);
return sum;
}
Function square()
int square(int a)
{
int sqr;
sqr=a*a;
return sqr;
}
void main()
{
int a=5,b=6;
int sumsqr;
sumsqr=add(a,b);
printf("%d",sumsqr);
}
Output:
61
In the above program when the compiler reaches the statement “sumsqr=add(a,b);” the compiler jumps to the
add() function and when the compiler reaches the statement “sum=square(a)+square(b);” it jumps to the
function square() two times, one time with the parameter as a and the other time the parameter as b.

First the value of 5*5 is calculated and the value 25 is returned to the sum() function and then the value of 6*6
is calculated and the value 36 is returned to the sum() function. Next the value of 25+36 is calculated in the
sum() function and the value 61 is returned to the main function.

5.1.10 Pre Defined Functions Vs User Defined Functions

Pre-Defined Function User Defined function


Pre-Defined functions are Library User defined functions are the
function. function which are created by user as
per his own requirements.
Pre-Defined functions are part of User defined functions
header file are part of the program which
(such as MATH.h) which is called compile runtime.
runtime.
Name of function can't be Name of function can be changed
changed. any time.
The declaration and definition of a User is going to declare and define
function is already known to the that function in the program.
compiler.
Example : add(), sub(), sum() Example: printf(), scanf(),
getch(),clrscr(), strlen(),strcpy();
5.1.11 Recursive Functions
A function that calls itself is called a recursive function. In a recursive function both the calling and the called
function is same. It follows LIFO (Last In First Out) data structure.
Example Program

int sum(int n);


void main()
{
int num=10;
add=sum(num);
printf("%d",add);
}
int sum(int n)
{
if(n==0)
return n;
else
return n+sum(n-1); //self call to function sum()
}
In the above example, the function sum() is invoked from the same function itself. If the value of n is not equal
to 0 then, the function calls itself passing an argument value, which is one less than the previous argument
value.

Suppose, n is 5 initially. Then, during next function calls, 4 is passed to function and the value of argument
decreases by 1 in each recursive call.

When, n becomes equal to 0, the value of n is returned which is the sum numbers from 5 to 1.

This is how recursion works

sum(5)
=5+sum(4)

=5+4+sum(3)

=5+4+3+sum(2)

=5+4+3+2+sum(1)

=5+4+3+2+1+sum(0)

=5+4+3+2+1+0

=5+4+3+2+1

=5+4+3+3

=5+4+6

=5+10

=15

Every recursive function must be provided with a way to end the recursion. In this example when, n is equal to
0, recursion function ends.

Note: Recursive function must have at least one terminating condition that can be satisfied.Otherwise, the
recursive function will call itself repeatedly until the run time stack overflows.

Example 2

Find the sum of all even numbers from 0 to 20 using function recursion.

Program:

#include<stdio.h>
void main()
{
int total;
total=sum(2);
printf("%d",total);
}
int sum(int i)
{
static int even=0;
if(i<=20)
{
even=even+i;
sum(i+2); //calling same function
}
return even;
}
Output
110

Disadvantages of recursion
 It is very slow process.
 function recursion can lead to infinite loop or stack over flow.

Example Program using Function


#include<stdio.h>

int validate(int age); // Function Declaration

void main()
{
int age,temp;
clrscr(); // predefined function
printf("\n\tEnter Your Age = ");
scanf("%d",&age);
temp = validate(age); //Function Calling
if(temp)
printf("\n\tYou are Eligible");
else
printf("\n\tYou are not Eligible");
getch(); // predefined function
}
int validate(int age) //Function Definition  user defined function
{
if(age>18)
return 1;
else
return 0;
}

5.2 Pointers

In C there are 2 Types of Variables :


1. Simple Variable that stores a value such as integer, float, character
Complex Variable that stores addresses of these simple variable i.e Pointer Variables

5.2.1 Introduction to Pointers

Variables in C generally hold value. An integer variable holds integer value. A floating point variable holds
floating point value. Similarly we need a data type to store the address of a variable and it is called as Pointer
variable.

Pointers are used in C program to access and manipulate the memory address.

Consider above Diagram :


1. i is the name given for Particular memory location(usually called as variable name) , and Corresponding
address of i is 65624 and the Value stored in variable ‘i’ is 5.

2. The address of the variable ‘i’ is stored in another integer variable ‘j’ and which is having 65522 as its
address.

The above diagram can be converted into code as follows

int i;
int *j; // j is a special pointer variable
i = 5;
j = &i; // i.e. j = Address of i

Note: The (&) is the address operator and it fetches the address of a
variable. A (*) symbol is appended before the variable name to notify the
compiler that it is the pointer variable.
Here j is not ordinary variable; It is special variable called pointer
variable as it stores the address of another ordinary variable.

Note: Pointer is a variable which stores the address of another variable

5.2.2 Need for Pointer

 It is used to store and access the address of memory location.


 The memory is used efficiently with the help of pointers.
 No other variables, other than the pointer variable can hold the address of a variable
5.2.3 Advantages and Disadvantages of Pointer
Advantages of Pointer

 Pointers save memory space.


 Execution time is faster because, pointers directly access the memory location.
 It is used in file handling.
 It allocates memory dynamically.

Disadvantages of Pointer

 Since it can access the address directly, it leads to security issues.


5.2.4 Pointer Declaration

Syntax

data type * variableName;

or

<pointer type> *<pointer-name>

In the above declaration :

1. Pointer-type: It specifies the type of pointer. It can be int, char, float etc. This type specifies the type of
variable whose address this pointer can store.

2. Pointer-name: It can be any name specified by the user. It is just like a variable name

The * is called the indirection operator or dereferencing operator.

Way of Declaring Pointer Variable

Example of Declaring Integer Pointer

int *x; // it holds only address of an integer variable.

Example of Declaring Float Pointer

float *f; // it holds only address of an float variable.

Example of Declaring Char Pointer

char *z; // it holds only address of an character variable.

Example of Declaring Double Pointer

double *d //it holds only address of an character variable.

The indirection operator serves two purpose

1. During declaration, the (*) indicates that it is a pointer variable and not a normal variable.
2. During dereferencing, the (*) indicates that, the value stored in the address, pointed by the pointer
should be accessed and not the value of the pointer(i.e the address)
The (&) is the address operator and it is used to retrieve the address of a variable.

Note: The * is used for the multiplication also but the compiler can differentiate whether it is used as a
multiplication operator or a pointer variable according to the context.

5.2.5 Pointer Initialization

Steps in initializing a pointer

1. Declare a Pointer Variable (remember the Data Type).

int *pointer;

2. Declare another Variable with Same Data Type as that of Pointer Variable.

int variable;

3. Initialize Ordinary Variable by assigning some value to it.

variable = 10;

4. Now initialize pointer by assigning the address of ordinary variable to pointer variable.

Pointer = &variable.

Example

int a=10; //Ordinary variable

int *b; //pointer variable

b = &a; // the address is allocated to the pointer variable

Let us see how the memory is allocated for the variable.

Variable a b

Value 10 1010

Address 1010 1012

Note: Whether it is an integer pointer or floating point every pointer variable requires only two bytes of
memory. Pointers are always initialized before using it in the program.
5.2.6 & and * Operator

The ‘*’ operator is used to obtain the value at the address contained by the pointer.

The ‘&’ operator is used to fetch the address of the variable.

Reference operator(&)

/* Example to demonstrate use of reference operator in C programming. */


#include <stdio.h>
void main()
{
int var=5;
printf("Value: %dd\n",var);
printf("Address: %d",&var); //Notice, the ampersand(&) before var.
}

Output
Value: 5
Address: 2686778

You will better understand the * and & operator with few more examples.

int a=10;

int *b;//pointer variable

b=&a;// the address is allocated to the pointer variable

Variable a b

Value 10 1010

Address 1010 1012

The following table show the possible ways to obtain the values using ‘*’ and ‘&’ operator.

Variable values Explanation


a 10 Value of a
Invalid Since ‘a’ is not a pointer variable
*a indirection and cannot be dereferenced.
Error
&a 1010 Address of a
b 1010 Value of b
Value that is stored in the address
*b 10
stored by the variable b
&b 1012 Address of a

Now let us see how double pointer a triple pointer works.

int a=10; // an integer variable


int *p1; //a pointer variable
p1=&a; //holds the address of a variable
int **p2; //double pointer
p2=&p1; // holds the address of a pointer
int ***p3; //triple pointer
p3=&p2; //holds the address of double pointer
A pointer will hold the address of a variable, a double pointer holds the address of a pointer, and a triple pointer
holds the address of a double pointer and so on.

Variable a p1 p2 p3

Value 10 1010 1012 1014

Address 1010 1012 1014 1016

Explanation

Variable values Explanation

a 10 Value of a.

p1 1010 Value of p1
p2 1012 Value of p2

p3 1014 Value of p3

&a 1010 address of a

&p1 1012 address of p1

&p2 1014 address of p2

&p3 1016 address of p3

Invalid a is normal variable and so


*a indirection cannot be dereferenced
Error

*p1 10 Value that is stored in the


address stored by the variable p1

*p2 1010 Value that is stored in the


address stored by the variable p2

*p3 1012 Value that is stored in the


address stored by the variable p3
Invalid p1 is a single pointer variable
**p1 indirection and so cannot be dereferenced as
Error a double pointer

Value that is stored in the

**p2 10 address, which is stored in the


address represented by variable
p2
Value that is stored in the

**p3 1010 address, which is stored in the


address represented by variable
p3
p2 is a double pointer variable
***p2 Invalid
and so cannot be dereferenced as
indirection
a double pointer
Error

Value that is stored in the


address, which is stored in the
***p3 10 another address, which is stored
in the address represented by
variable p3
Some important points about De-Reference Operator:

1. Value at Operator (*) is unary operator when use in pointer.

2. Multiplication Operator (*) is binary operator when used for multiplication.

3. The operator ‘*’ in pointer concept is also called as “De-reference” Operator Or “Value at Operator“

Precedence and associativity of ‘* ‘and ‘&‘ Operator.

1. Both are Unary Operators

2. They have Equal Precedence

3. They Associate from Right –> Left

Example Program
//Handling of pointers in C program
1 #include <stdio.h>
2 void main()
3 {
4 int *pc,c;
5 c=22;
6 printf("Address of c:%d\n",&c);
7 printf("Value of c:%d\n\n",c);
8 pc=&c;
9 printf("Address of pointer pc:%d\n",pc);
10 printf("Content of pointer pc:%d\n\n",*pc);
11 c=11;
12 printf("Address of pointer pc:%d\n",pc);
13 printf("Content of pointer pc:%d\n\n",*pc);
14 *pc=2;
15 printf("Address of c:%d\n",&c);
16 printf("Value of c:%d\n\n",c);
17 }

Output
Address of c: 2686784
Value of c: 22

Address of pointer pc: 2686784


Content of pointer pc: 22

Address of pointer pc: 2686784


Content of pointer pc: 11

Address of c: 2686784
Value of c: 2
Explanation of program and figure

1. Code int *pc, p; creates a pointer pc and a variable c. Pointer pc points to some address and that address
has garbage value. Similarly, variable c also has garbage value at this point.

2. Code c=22; makes the value of c equal to 22, i.e., 22 is stored in the memory location of variable c.

3. Code pc=&c; makes pointer pc point to address of c. *pc (value at address pointed by pc) will be equal
to the value of c.

4. Code c=11; makes the value of c as 1. Now Value of *pc will also be 11.

5. Code *pc=2; change the address pointed by pointer pc to change to 2. Since, address of pointer pc is
same as address of c, value of c also changes to 2.

5.2.7 Pointer Arithmetic

Two possible arithmetic operations in the pointers are addition and subtraction.

Formula : (addition)
New address = current address + added value * size_of(data type)
new address = 1012 + 4*2 variale a p int a=10;
= 1020 value 10 1012
int *p;
p =&a;
address 1012 1014 p = p + 4;

Formula : ( Decrementing)
new address = current address - subtracted value * size_of(data type)
new address = 1012 - 4*2
= 1004

Data Type Older Address stored in pointer Next Address stored in pointer after incrementing (ptr++)
int 1000 1002
float 1000 1004
char 1000 1001
 Incrementing a pointer to an integer data will cause its value to be incremented by 2 bytes .
 Incrementing a pointer to an float data will cause its value to be incremented by 4 bytes

If we will add or subtract a number from an address result will also be an address.
 If we increment a pointer ,it moves to the address of the next element(it moves I byte if it is a character
pointer, 2 bytes if it is an integer pointer and 4 bytes if it is a floating point pointer ).
 If we decrement a pointer, it moves to the address of the previous element(it moves I byte if it is a
character pointer, 2 bytes if it is an integer pointer and 4 bytes if it is a floating point pointer ).

Consider the example below

Increment Integer Pointer


#include<stdio.h>
void main()
{
int *ptr=(int *)1000;// type casting integer value to integer pointer
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
}
Output

New Value of ptr : 1002

Increment Double Pointer


#include<stdio.h>
void main()
{
double *ptr=(double *)1000; type casting integer value to double
pointer
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
}
Output

New Value of ptr : 1004


Explanation

Address of ptr[0] = 1000

Address of ptr[1]

= Address of ptr[0] + (Size of Data Type)

= 1000 + (4 bytes)

= 1004

5.2.8 Pointer and Array

An array and pointer go hand in hand with each other. An array can be accessed by using pointer. Arrays and
pointers are synonymous in terms of how they use to access memory. But, the important difference between
them is that, a pointer variable can take different addresses as value whereas, in case of array it is fixed.

Relation between Arrays and Pointers


Array elements are stored in consecutive memory location.

Example 1

Consider and array:

int arr[4];

In arrays of C programming, name of the array always points to the first element of an array. Here, address of
first element of an array is &arr[0].arr represents the address of the pointer where it is pointing. Hence,
&arr[0] is equivalent to arr.

The statement

int arr[1]={10};

is

equivalent to

int *arr;
arr[0]=10;

arr = &a[0];

Similarly,

&a[1] is equivalent to (a+1) AND, a[1] is equivalent to *(a+1).

&a[2] is equivalent to (a+2) AND, a[2] is equivalent to *(a+2).

&a[3] is equivalent to (a+1) AND, a[3] is equivalent to *(a+3).

&a[i] is equivalent to (a+i) AND, a[i] is equivalent to *(a+i).

In C, you can declare an array and can use pointer to access the elements of an array.

Program

//Program to find the sum of six numbers with arrays and pointers.

#include <stdio.h>
void main()
{
int i,class[6],sum=0;
printf("Enter 6 numbers:\n");
for(i=0;i<6;++i)
{
scanf("%d",(class+i)); // (class+i) is equivalent to &class[i]
sum += *(class+i); // *(class+i) is equivalent to class[i]
}
printf("Sum=%d",sum);
}
Output

Enter 6 numbers:
2
3
4
5
3
4
Sum=21

Example 2

int a[5]={10,20,30,40,50};

Variable a[0] a[1] a[2] a[3] a[4]

Value 10 20 30 40 50

Address 1010 1012 1014 1016 1018

Here a[0] is the starting element and the address of a[0] is called the base address

Value of a[0] = 10.

Value of a[1] = 20.

Value of a[2] = 30.

Value of a[3] = 40.

Value of a[4] = 50.

Then Value of a =?

Now what will the variable ‘a’ hold and what will happen when the value of ‘a’ is printed?

Consider the statement below,

printf(“%d”,a);

The output of the statement would be “1010” since an array variable will hold the base address;

Now when we declare a variable as

int a[5];

something equivalent to the following will happen within the compiler implicitly (i.e. the statements will not be
visible but will happen within the compiler )

int *a;// an array variable will be considered as pointer


a = &a[0];// the base address of an array will be stored in the variable a.

Then value of a = &a[0] (address of first array variable)

Let us see how the elements of the array are accessed using pointer. As we know the array variable ‘a’ is also
considered as pointer and it will hold the variable a[0].

If we increment the array variable a, then it will move to the next element.

a =>contains the address of the first element.

*a =>contains the value of the first element.

It means a[0] = 10

a+1=> contains the address of the second element

*(a+1) =>contains the value of the second element.

It means a[0]+1 = a[1] .= 20

a+2=> contains the address of the third element

*(a+2) =>contains the value of the third element

It means a[0]+2 = a[2] = 30 .

a+3=> contains the address of the fourth element

*(a+3) =>contains the value of the fourth element

It means a[0]+3 = a[3] = 40.

a+4=> contains the address of the fifth element.

*(a+4) =>contains the value of the fifth element

It means a[0]+4 = a[4] = 50 .

Using dereferencing pointer, we can access the value of elements as follows.

*a or a[0] 10
*(a+1) or a[1] 20
*(a+2) or a[2] 30
*(a+3) or a[3] 40
*(a+4) or a[4] 50
5.2.9 Pointer to Functions (Function Pointer)
 A pointer which keeps address of a function is known as Function Pointer.
 No function can return more than one value. But using pointers we can return more than one value.
Consider the example below, let us try to return two values at a time

void main()
{
int a=10,b=5;
a,b=square(a,b);//this is meaningless and not supported by c
printf("%d %d",a,b);
}
void square(int j,int k)
{
j=j*j;
k=k*k;
return(j,k);//Error: a function cannot return two values at a time.
}
(Actual (Formal
Variable Parameter) Parameter)

a b j k

Value 10 5 100 25

Address 1010 1012 1014 1016

The above example illustrates that it is not possible to return two values and without returning the values, the
updated values will not be reflected in the main function.

So using pointer, we pass the address of the value and in the called function when the value is updated, it will
directly updating in the memory location and so it will be reflected in the main function.

Example 1

#include <stdio.h>
void main()
{
int a=10,b=5;
square(&a,&b);//the address is passed
printf("%d %d",a,b);
}
void square(int *j,int *k)
{
*j=(*j)*(*j); // updation is done directly in the memory location of variable a.
*b=(*b)*(*b); // updation done directly the memory location of variable b .
}
Variable (actual (ptr variable)
parameter)
a b *j *k
Value 10 5 100 25
Address 1010 1012 1010 1012
Explanation:

&a and j refers to same memory location and hence any updates done using the pointer variable j will
affect the value of a.

&b and k refers to same memory location and hence any updates done using the pointer variable k will
affect the value of b.

Output

100 25

5.2.10 Pointer to Structure

A pointer which is pointing to a structure is known as Pointer to Structure.

Structure's member can be accessed through pointer.

Consider an example to access structure's member through pointer.

Example 1

Using dot(.) operator:


#include <stdio.h>
struct book
{
int pages;
float price;
};
void main()
{
struct book *ptr;
struct book p;
ptr=&p; /* Referencing pointer to memory address of p */
printf("Enter no of pages: ");
scanf("%d",&(*ptr).pages); // (*ptr).pages is equivalent to p.pages
printf("Enter price: ");
scanf("%f",&(*ptr).price); // (*ptr).price is equivalent to p.price
printf("/nDisplaying:/n ");
printf("%d %f",(*ptr).pages,(*ptr).price);
}
Output:
Enter no of pages:450
Enter price: 220.75
Displaying:
450 220.75

In this example, the pointer variable of type struct is referenced to the address of p. Then the structure member
is accessed through pointer using dot operator.

Structure pointer member can also be accessed using -> operator.

(*ptr).a is same as ptr->a


(*ptr).b is same as ptr->b
-> and (*). Both represent the same but  operator will not have ‘*’ in front.

These operators are also used to access data member of structure by using structure’s pointer.

Example 2
#include <stdio.h>
struct book
{
int pages;
float price;
};
void main()
{
struct book *ptr;
struct book p;
ptr=&p; /* Referencing pointer to memory address of p */
printf("Enter no of pages: ");
scanf("%d",&ptr->pages); // (*ptr).pages is equivalent to p.pages
printf("Enter price: ");
scanf("%f",&ptr->price); // (*ptr).price is equivalent to p.price
printf("/nDisplaying:/n ");
printf("%d %f",ptr->pages,*ptr->price);
}
Output:
Enter no of pages:450
Enter price: 220.75
Displaying:
450 220.75

5.2.11 Void Pointer

void pointer is a pointer that can store the address of any type of variable

Introduction

 Suppose if we have to declare integer pointer, character pointer and float pointer then we need to declare
3 pointer variables.

 Instead of declaring different types of pointer variable it is possible to declare single pointer variable
which can act as integer pointer, character pointer or floating point pointer.

This General Purpose Pointer Variable is Called as void Pointer.


Advantages of void pointer

 It does not have any data type associated with it

 It can store address of any type of variable.

Declaration of void Pointer

Syntax:

void * pointerVaraibleName;

Example :

void *ptr;

Consider the below example to clearly understand the void pointer

void *ptr; // ptr is declared as Void pointer

char cnum;

int inum;

float fnum;

ptr = &cnum; // ptr has address of character data

ptr = &inum; // ptr has address of integer data

ptr = &fnum; // ptr has address of float data

Explanation:

We have declared 3 variables of integer, character and float type.

 When we assign address of integer to the void pointer, pointer will become Integer Pointer.

 When we assign address of Character Data type to void pointer it will become Character Pointer.

 When we assign address of floating point Data type to void pointer it will become floating point
Pointer

 It is capable of storing address of any data type

5.2.12 Null Pointer

 A Pointer which does not point to any memory location is called NULL Pointer.
Meaning of NULL

 NULL is macro constant which has been defined in the header file stdio.h, alloc.h, mem.h, stddef.h and
stdlib.h as #define NULL 0

Example
int *a;
int *b = NULL;

here ‘*a’ and ‘*b’ are not same because b points to NULL and a may point to some garbage address

( a == b ) FALSE ,in most cases


(a == NULL ) FALSE,in most case
(b == NULL ) ALWAYS true

Example program:
Void main()
{
int *a;
int *b =NULL;
printf(“value of a =%d \t value of b =%d”,a,b);
}
Output:

Value of a = 28620 value of b = 0

NULL is a reserved word in most high-level languages. It is an EXPLICIT value, and not an "undefined"
value.

5.2.13 Wild Pointer


A pointer in c which has not been initialized is known as wild pointer.

Example:

What will be output of following c program?

#include<stdio.h>
void main()
{
int *p;
printf("%u\n",p);
}

Output:
28618
Here the output is just any random address (Garbage value)
Here p is wild pointer because it has not been initialized. Wild pointer doesn’t point any specific memory
location.

5.2.14 Dangling Pointer


If a pointer is pointing to the memory address of a variable and after sometimes, if the variable has been deleted
from that memory location, then the pointer will be still pointing to the same memory location. Such pointer is
known as dangling pointer and this problem is known as dangling pointer problem.

Initially:

Later:

5.2.15 far Vs near


The pointer which can point or access whole the residence memory of RAM i.e. which can access all 16
segments is known as far pointer. The size of far pointer is 4 bytes.

The pointer which can point or access only 64KB data segment of RAM i.e. which can access only 8 segments
is known as far pointer. The size of far pointer is 4 bytes.

Difference between void pointer, NULL pointer, wild pointer and dangling pointer.

void pointer NULL pointer wild pointer dangling pointer

It can point to memory It points to a NULL It points to any random It points to a memory
address of any type of value. address(garbage value) address of a variable,
variable. which has been deleted

You might also like