0% found this document useful (0 votes)
8 views19 pages

unit-4

The document provides an overview of functions in C programming, emphasizing their importance in structuring programs into manageable segments. It explains the types of functions, including standard library functions and user-defined functions, and outlines the process of function declaration, definition, and calling. Additionally, it discusses parameter passing methods, such as call by value and call by address, with examples to illustrate these concepts.

Uploaded by

ps9422495
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)
8 views19 pages

unit-4

The document provides an overview of functions in C programming, emphasizing their importance in structuring programs into manageable segments. It explains the types of functions, including standard library functions and user-defined functions, and outlines the process of function declaration, definition, and calling. Additionally, it discusses parameter passing methods, such as call by value and call by address, with examples to illustrate these concepts.

Uploaded by

ps9422495
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/ 19

KUMAR NAGISETTI

UNIT-4
INTRODUCTION
The programs written in C language are highly dependent on functions. The C program is nothing but
the combination of one or more number of functions. Every C program starts with the user defined function
main(). The main() calls other functions to share the work. ‘C’ programmers to break-up a program into
segments commonly known as functions. Every function in the program is supposed to perform a well-
defined task.

main()
{
func1( )
…………
{
…………
Statementblock;
func1();
………… }

…………
return0;
}

Form the diagram, main () calls the func1.Therefore, main () is known as the calling function and func1 is
known as the called function.
Definition of the function:
The function is a sub program or sub routine or self contained block of one or more executable statement, which
performs a well defined task. We have two types of functions.
1. Standard/Pre Defined/Library Functions.
2. User Defined Functions.
Need for functions:
 Divide the program into separate well-defined functions facilitates each function to be written and
tested separately.
 From the diagram main( ) calls other functions for dividing the entire code into smaller functions.
This approach is referred to as ‘top down approach’.

Main function

Function A Function B Function C

Function B1 Function B2

 Understanding, coding and testing multiple separate functions are far easier than doing the same for
one huge function.
 It is big program has to be developed without the use of any function other than main( ), then there
will be countless lines in the main( ) and maintaining this program will be very difficult. A large
program size is a serious issue in micro computers where memory space is limited.
SEMESTER I::Problem Solving in C Page 1
KUMAR NAGISETTI

 All the libraries in ‘C’ contain a set of functions that the programmers are free to use in their
programs. These functions have been pre-written and pre-tested, so the programmers can use them
without worrying about their code details.
 When a big program is broken into smaller functions then different programmers working on that
project can divide the workload by writing different functions.
 Similar to C libraries, programmers can from different points in the main program or any other
program that needs its functionalities.
Using functions:
In C program, the operating system calls the main() of the program which marks then try point for the
execution. When the program is executed, main( ) returns some value to the operating system.
Using functions we will be using the following terminologies.
 A function f()that uses another function g(), is known as the calling function.
 The inputs that the function takes are known as arguments or parameters.
 When the called function returns some result back to the calling function. It is said to return that result.
 The calling function mayor may not pass parameters to the called function. If the called function accepts
arguments, the calling function will pass parameters.
 Function declaration is a declaration statement that identifies a function with its name, a list of arguments
that it accepts, and the type of data it returns.
 Function definition consists of a function header that identifies the function followed by the body of the
function containing the executable code for that function
**********************************************************************************
Types of functions:
There are two types of functions in C:
1. Library Functions
2. User Defined Functions

1. Pre-defined functions(or) Library functions(or)built-in functions:


A function which is pre-defined is a library function. A library function can be represented with a
function name followed by a list of arguments separated by comma operator within the parenthesis.
A pre-defined statement should be included in the program to work with this library functions. These
functions can perform input and output operations, mathematical operations, operations on character and
strings etc.,
The following are the various library functions:
The preprocessor for all the below functions is #include<math.h>
1. abs(variable): Gives the absolute value of an integer.
Ex:abs(-2)=2
2. fabs(variable): Gives the absolute value of a floating point number.
Ex:fabs(-2.5)2.5
3. ceil(variable): Gives the round of the value.
Ex:ceil(3.5)=4.0
4. floor(varible): Gives the truncate the decimal value.
Ex:ceil(3.2)=3.0
5. sqrt(variable): Gives the square root value.
Ex:sqrt(25)=5
6. pow(variable): Gives the value of power.
Ex:pow(3,2)=9
7. log(variable): Gives the natural logarithm value.
Ex:log(0)=1
SEMESTER I::Problem Solving in C Page 2
KUMAR NAGISETTI

2. User defined functions:.


Every user defined function must have the following components.
1. Function prototype (or) Function Declaration.
2. Function Call.
3. Function Definition.
Function declaration (or) Function prototype: The general format for declaring a function that accepts some
arguments and returns some value as a result can be given as:
return_data_typefunction_name(data_typevariable1,data_typevariable2,…….,);
The following points should keep in mind about the function declaration.
 After the function declaration of every function there should be a semicolon (;).
 The function declaration is global. Therefore the declaration function cans be called from any point in
the program.
Ex: int func(int,char, float); OR Int func(int a, char ch,float b);
Function having ‘void’ as its return type cannot return any value.
Function call: The function call statement invokes the function. When a function is invoked the compiler
jumps to the called function to execute the statements that are a part of that function. Once the called
function is executed, the program control passes back to the calling function.
Syntax:
The function call statement has the following syntax:
function_name(variable1,variable2…….);
Function definition:
When a function is defined, space is allocated for that function in the memory. A function definition has two
parts:
 Function header.
 Function body.
The syntax of a function definition can be given as
return_data_typefunction_name (data_typevariable1, data_typevariable2………)
{
……………………
……………………
…………………...
…………………...
return (variable)
}
The function header is same as that of the function declaration. The only difference between the two
is that a function header is not followed by a semicolon(;).
 return data type: The type of the value returned by the function is return data type. If a function
returns integer value return type is int, if a function returns float value return type is float, if a
function return nothing return type is void.
 Function name: Every function must have a name. A function is defined by its name. no two
functions in the program can have same name, function name must be unique. Function name must
be user defined word but not keyword.
 Arguments or parameters: A parameter is a input to the function. Function may have 0, 1or more
parameters.
Ex: To find largest of two numbers, function must have two parameters. i.e., max(a,b);

SEMESTER I::Problem Solving in C Page 3


KUMAR NAGISETTI

Parameters

Actual parameters Formal parameters

Formal parameters are the parameters declared in the brackets in function definition after the function
name. When any function is being called from the main program, the parameters used in the calling are
called the actual parameters, which are individually declared in the main program. These actual parameters
are converted to formal parameters when the control goes to the function.
Ex: main()
{
f1(10,20.8,‘g’)/*AP*/
}
f1(int x, float y, char ch’)/*FP*/
{
……………..
………….....
}
return statement: A function can return value by return statement. A function can return more than one
value from the function.
Syntax:
return(value/expression/variable);
return;
Ex:
1. return 25;
25is return to function call.
2. return;
nothing is returned(void function)
The following program gives a brief explanation on user defined functions.
Aim: To write a C program to illustrate the user defined functions in C
#include<stdio.h>
int sum(int, int);
void main()
{
int a, b, c;
printf("\n Enter two
integers:"); scanf("%d %d",
&a, &b); c=sum(a, b);
printf("\n The sum is %d",
c);
}
int sum(int x, int y)
{
int z;
z=x+y;
return z;
}
****************************************************************************
SEMESTER I::Problem Solving in C Page 4
KUMAR NAGISETTI

Types of user-defined functions:


A function may belong to one of the following categories:
1. Function with no parameters and no return values
2. Function with no parameters and return values.
3. Function with parameters and no return values
4. Function with parameters and return values
1. Function with no parameters and no return values
(void function without parameter)
Calling function Called function
/*program to find sum of two numbers using void add()
functions*/ {
#include<stdio.h> int a, b, sum;
void add(); printf("Enter two numbers: ");
void main() scanf("%d %d", &a, &b);
{ sum = a + b;
add(); printf("The sum is: %d\n", sum);
} }

 In this category no data is transferred from calling function to called function, hence
called function cannot receive any values.
 In the above example, no arguments are passed to user defined function add().
 Hence no parameter is defined in function header.
 When the control is transferred from calling function to called function a, and b values
are read, they are added, the result is printed on monitor.
 When return statement is executed, control is transferred from called function/add to calling
function/main.

2. Function with no parameters and return values.


(void function with parameter)
Calling function Called function
/*program to find sum of two numbers using int add( )
functions*/ {
#include<stdio.h> int a, b;
int add(); printf("Enter two numbers: ");
void main() scanf("%d %d", &a, &b);
{ return a + b;
int result = add(); }
printf("The sum is: %d\n", result);
}
 In this category there is no data transfer from the calling function to the called
function.
 But, there is data transfer from called function to the calling function.
 No arguments are passed to the function add().So, no parameters are defined in the
function header
 When the function returns a value, the calling function receives one value from the
called function and assigns to variable result.
 The result value is printed in calling function

SEMESTER I::Problem Solving in C Page 5


KUMAR NAGISETTI

3. Function with parameters and no return values


Calling function Called function
/*program to find sum of two numbers using void add(int a, int b)
functions*/ {
#include<stdio.h> int sum = a + b;
void add(int, int); printf("The sum is: %d\n", sum);
void main() }
{
int x, y;
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);
add(x, y);
}
 In this category, there is data transfer from the calling function to the called function
using parameters.
 The values of actual parameters x and y are copied into formal parameters a and b.
 The value of a and b are added and result stored in sum is displayed on the screen in called
function itself.

4. Function with parameters and return values


Calling function Called function
/*program to find sum of two numbers using functions*/ int add(int a, int b)
#include<stdio.h> {
int add(int, int); return a + b;
void main() { }
int x, y, result;
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);
result = add(x, y);
printf("The sum is: %d\n", result);
}
 In this category, there is data transfer from the calling function to the called function
using parameters.
 When Actual parameters values are passed, the formal parameters in called function
can receive the values from the calling function.
 When the add function returns a value, the calling function receives a value from the called
function.
 The values of actual parameters m and n are copied into formal parameters a and b.
 Sum is computed and returned back to calling function which is assigned to variable result.
Passing parameters to functions or Types of argument passing
The different ways of passing parameters to the function are:
1) Pass by value (or) Call by value
2) Pass by address (or) Call by address
Call by value:
a. In call by value, the values of actual parameters are copied into formal parameters.
b. The formal parameters contain only a copy of the actual parameters.
c. So, even if the values of the formal parameters changes in the called function, the
values of the actual parameters are not changed.
d. The concept of call by value can be explained by considering the following program
SEMESTER I::Problem Solving in C Page 6
KUMAR NAGISETTI

Example:
#include<stdio.h> OUTPUT:
void swap(int x, int y) Before function call: a = 10, b = 20
{ Inside function (after swap): x = 20, y = 10
int temp = x; After function call: a = 10, b = 20
x = y;
y = temp;
printf("Inside function (after swap): x = %d, y = %d\n", x, y);
}
void main()
{
int a = 10, b = 20;
printf("Before function call: a = %d, b = %d\n", a, b);
swap(a, b);
printf("After function call: a = %d, b = %d\n", a, b); // No change in values
}
 Execution starts from function main() and we will read the values for variables a and b,
assume we are reading 10 and 20 respectively.
 We will print the values before swapping it will print 10 and 20.
 The function swap() is called with actual parameters a=10and b=20.
 In the function header of function swap(),the formal parameters x and y receive the
values 10 and20.
 In the function swap(), the values of x and y are exchanged.
 But, the values of actual parameters a and b in function main() have not been exchanged.
 The change is not reflected back to calling function.
Call by Address:
 In Call by Address, when a function is called, the addresses of actual parameters are sent.
 In the called function, the formal parameters should be declared as pointers with the same
type as the actual parameters.
 The addresses of actual parameters are copied into formal parameters.
 Using these addresses the values of the actual parameters can be changed.
 This way of changing the actual parameters indirectly using the addresses of actual
parameters is known as pass by address.
Example:
#include <stdio.h>
void swap(int *x, int *y) OUTPUT:
{ Before swapping: a = 10, b = 20
int temp = *x; After swapping: a = 20, b = 10
*x = *y;
*y = temp;
}
void main()
{
int a = 10, b = 20;
printf("Before swapping: a = %d, b = %d\n", a, b);
swap(&a, &b); // Passing addresses of a and b
printf("After swapping: a = %d, b = %d\n", a, b); // Values are swapped
return 0;
}

SEMESTER I::Problem Solving in C Page 7


KUMAR NAGISETTI

Differences between Call by Value and Call by reference


Call by Value Call by Address
When a function is called the values of variables are When a function is called the addresses of variables are
passed passed
The type of formal parameters should be same as The type of formal parameters should be same as type of
type of actual parameters actual parameters, but they have to be declared as pointers.
Formal parameters contains the values of actual Formal parameters contain the addresses of actual
parameters parameters.
Differences between Actual Parameters and Formal Parameters
Actual Parameters Formal Parameters
Actual parameters are also called as argument list. Formal parameters are also called as dummy
Ex: add(m,n) parameters. Ex:int add(int a, int b)
The variables used in function call are called as The variables defined in function header are
actual parameters The variables defined in parameters
function header are parameters
Actual parameters are used in calling function Formal parameters are used in the function header of
when a function is called or invoked a called function.
Ex: add(m,n) Example: int add(int a, int b)
Here, m and n are called actual parameters { ……….. }
Here, a and b are called formal parameters.
Actual parameters sends data to the formal Formal parameters receive data from the actual
parameters parameters.
Storage Classes in C
In C, storage classes define the lifetime, scope, and visibility of variables. They specify where a variable is stored,
how long its value is retained, and how it can be accessed which help us to trace the existence of a particular
variable during the runtime of a program.
In C, there are four primary storage classes:
 auto
 register
 static
 extern
 auto
This is the default storage class for all the variables declared inside a function or a block. Auto variables can be
only accessed within the block/function they have been declared and not outside them (which defines their scope).
Properties of auto Variables
Scope: Local
Default Value: Garbage Value
Memory Location: RAM
Lifetime: Till the end of its scope
#include <stdio.h>
Output
int main()
10
{
auto int x = 10;
printf("%d", x);
return 0;
}
Explanation: The auto keyword is used to declare a local variable with automatic storage. However, in C, local
variables are automatically auto by default, so specifying auto is optional.
auto keyword is not used in front of functions as functions are not limited to block scope.
SEMESTER I::Problem Solving in C Page 8
KUMAR NAGISETTI

 static
This storage class is used to declare static variables that have the property of preserving their value even after they
are out of their scope! Hence, static variables preserve the value of their last use in their scope.
Properties of static Storage Class
Scope: Local
Default Value: Zero
Memory Location: RAM
Lifetime: Till the end of the program
#include <stdio.h>
void counter()
{ Output
static int count = 0; Count = 1
count++; Count = 2
printf("Count = %d\n", count);
}
int main()
{
counter();
counter();
return 0;
}
Explanation: The static variable count retains its value between function calls. Unlike local variables, which are
reinitialized each time the function is called, static variables remember their previous value.
 register
This storage class declares register variables that have the same functionality as that of the auto variables. The only
difference is that the compiler tries to store these variables in the register of the microprocessor if a free register is
available making it much faster than any of the other variables.
Properties of register Storage Class Objects
Scope: Local
Default Value: Garbage Value
Memory Location: Register in CPU or RAM
Lifetime: Till the end of its scope
Note: The compiler may ignore the suggestion based on available registers.
#include <stdio.h>
int main() { Output
register int i; 01234
for (i = 0; i < 5; i++) {
printf("%d ", i);
}
return 0;
}
Explanation: The register keyword suggests storing the variable in a register for faster access, but the compiler may
not always honor this request based on available CPU registers.
 extern
Extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is
used. Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different
block as well.
Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword before its
declaration/definition in any function/block.
Properties of extern Storage Class Objects
SEMESTER I::Problem Solving in C Page 9
KUMAR NAGISETTI

Scope: Global
Default Value: Zero
Memory Location: RAM Output
Lifetime: Till the end of the program. 20
For example, the below file contains a global variable.
#include <stdio.h>
int a = 20;
int main()
{
extern int a;
printf("%d",a);
}
Discuss about scope of variables?
In C. all constants and variables have a defined scope. By scope we mean the accessibility and visibility of the
variables at different points in the program. A variable or a constant in C has four types of scope:
1) Block scope,
2) Function scope,
3) Program scope,
4) File scope
Block scope:We know that a statement block is a group of statements enclosed within opening and closing
braces({}). If a variable is declared within a statement block then, as soon as the control exists that block, the
variable will cease to exist. Such a variable, also known as a local variable, is said to have a block scope.
For example, if we declare an integer x inside a function, then that variable is unknown to the rest of the
program (i.e., outside that function).
#include <stdio.h>
int main() { Output
int x = 10, i = 0; // Outer x = 10 The value inside the while loop is 0
while (i < 3) { The value inside the while loop is 1
int x = i; // Local x (shadows outer x) The value inside the while loop is 2
printf("\n The value inside the while loop is %d", x); The value of x outside the while loop is 10
i++;
}
printf("\n The value of x outside the while loop is %d", x);
return 0;
}
Function Scope: Function scope indicates that a variable is active and visible from the beginning to the end of a
function. In C, only the goto label has function scope. In other words function scope is applicable only with goto
label names. This means that the programmer cannot have the same label name inside a function.
#include <stdio.h>
void func(int a) { // a is local to func()
Output
printf("Inside func: a = %d\n", a);
} Inside func: a = 5
int main() {
int x = 5;
func(x); // Passing x to func()
return 0;
Program scope: Local variables (also known as internal variables) are automatically created when they are
declared in the function and are usable only within that function. The local variables are unknown to other
functions in the program. Such variables cease to exist after the last statement in the function in which they are
declared and are re-created each time the function is called.
SEMESTER I::Problem Solving in C Page 10
KUMAR NAGISETTI

However, if you want this function to access some variables which are not passed to them as arguments, then
declare those variables outside any function blocks. Such variables are commonly known as global variables and
can be accessed from any point in the program.
Example:
#include <stdio.h>
int x = 10;
void print();
int main() {
printf("\n The value of global x in main() = %d", x); Output
int x = 2; The value of global x in main() = 10
printf("\n The value of local x in main() = %d", x); The value of local x in main() = 2
print(); The value of global x in print() = 10
return 0;
}
void print()
{
printf("\n The value of global x in print() = %d", x); // Uses global x
}
File scope: When a global variable is accessible until the end of the file, the variable is said to have file scope. To
allow a variable to have file scope, declare that variable with the static keyword before specifying its data type, as
shown:
static int x = 10;
A global static variable can be used anywhere from the file in which it is declared but it is not accessible by
any other files. Such variables are useful when the programmer writes his/her own header files.
Difference Between Local and Global Variables in C
Feature Local Variable Global Variable
Scope Inside the function/block where it is declared Entire program (all functions)
Lifetime Created when function is called, destroyed Exists throughout the program execution
when function exits
Memory Storage Stored in stack memory Stored in data segment (global/static
memory)
Access Only accessible inside the function/block Accessible from any function in the program
Default Value Garbage value (if uninitialized) Zero (0) (if uninitialized)
Declaration Inside a function or block Outside all functions
Location
Usage Used for temporary, function-specific data Used for data that needs to be shared across
multiple functions
#include <stdio.h>
int globalVar = 10;
void function() {
int localVar = 20; // Local variable (only inside function)
printf("Inside function: Local Variable = %d\n", localVar);
printf("Inside function: Global Variable = %d\n", globalVar);
} Output
void main() { Inside main: Local Variable = 5
int localVar = 5; // Local to main() Inside main: Global Variable = 10
printf("Inside main: Local Variable = %d\n", localVar); Inside function: Local Variable = 20
printf("Inside main: Global Variable = %d\n", globalVar); Inside function: Global Variable = 10
function();
}
SEMESTER I::Problem Solving in C Page 11
KUMAR NAGISETTI

Explain the concept of recursion functions with an example?


A. Recursion: Recursion is a process by which a function calls itself repeatedly, until some specified
condition has been satisfied. The process is used for repetitive computations in which each action is stated in terms
of a previous result. Many iterative (i.e repetitive) problems can be written in this form.
In order to solve a problem recursively two conditions must be satisfied. First, the problem must be written in
a recursive form, and second, the problem statement must include a stopping condition.
When writing recursive functions we must have a conditional statement somewhere in the function to force
the function to return without the recursive call being executed otherwise the function will never return and
program goes into infinite loop.
#include <stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{ Output:
Enter the number whose factorial you want to calculate?5
return 0; factorial = 120
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}

Types of recursion?
Recursion is a technique that breaks a problem into one or more sub-problems that are similar to the original
problem. Any recursive function can be characterized based on the following:
1. Direct Recursion: A function is said to be directly recursive if it explicitly calls itself. For example,
int func (int n)
{
if (n=0)
return n;
return (func(n-1));
}
Here, the function func() calls itself for all positive values of n, so it is said to be a directly recursive function.
2. Indirect Recursion: A function is said to be indirectly recursive if it contains a call to another function which
ultimately calls it. Look at the functions given. below. These two functions are indirectly recursive as they both call
each other.

SEMESTER I::Problem Solving in C Page 12


KUMAR NAGISETTI

int Func1 (int n)


{
if (n=0)
return n;
return Func2 (n);
}
int Func2 (int x)
{
return Funcl (x-1);
}
3. Tail Recursion: A recursive function is said to be tail recursive if no operations are pending to be performed
when the recursive function returns to its caller. When the called function returns, the returned value is immediately
returned from the calling function. Tail recursive functions are highly desirable because they are much more efficient
to use as the amount of information that has to be stored on the system stack is independent of the number of
recursive calls.
int Fact (int n)
{
if (n=1)
return 1;
return (n* Fact (n-1));
}
4. Linear and Tree Recursion: Recursive functions can also be characterised depending on the way in which the
recursion grows in a linear fashion or forming a tree structure.
int Fibonacci (int num)
{
if (num <=2)
return 1;
return (Fibonacci (num-1) + Fibonacci (num -2));
}

SEMESTER I::Problem Solving in C Page 13


KUMAR NAGISETTI

1. What is a pointer? What are the uses of pointers in C


Pointer data type is one of the strengths of the C language. The pointer is a powerful technique to access the
data by indirect reference as it holds the address of the variable where it has been stored in the memory.
A pointer is a variable which holds the memory address of another variable. Sometimes, only with the pointer
a complex data type can be declared and accessed easily.
Advantages
 Pointers are used for dynamic memory allocation and deallocation.
 An Array or a structure can be accessed efficiently with pointers
 Pointers are useful for accessing memory locations.
 Pointers are used to form complex data structures such as linked lists, graphs, trees, etc.
 Pointers reduce the length of the program and its execution time as well.
Disadvantages
 Pointers are vulnerable to errors and have following disadvantages:
 Memory corruption can occur if an incorrect value is provided to pointers.
 Pointers are a little bit complex to understand.
 Pointers are majorly responsible for memory leaks in C.
 Pointers are comparatively slower than variables in C.
 Uninitialized pointers might cause a segmentation fault.
What is a pointer? How pointer is declared and initialized in C ?
C provides data manipulation with addresses of variables therefore execution time is reduced. Such concept
is possible with special data type called pointer. A pointer is a variable which holds the address of another variable
or identifier this allows indirect access of data.
1. Declaring pointer variables
In C, every variable must be declared for its type. Since pointer variables contain addresses that belong to a
separate data type, they must be declared as pointers before we use them. The declaration of a pointer variable
takes the following form:
data_type *pt_name;
This tells the compiler three things about the variable pt_name.
1. The asterisk (*) tells that the variable pt_name is a pointer variable.
2. pt_name needs a memory location.
3. pt_name points to a variable of type data_type.
For example,
int *p; /* integer pointer */
declares the variable p as a pointer variable that points to an integer data type.
2. Intialization of pointer variables
The process of assigning the address of a variable to a pointer variable is known as initialization. The
programs with uninitialized pointers will produce erroneous results.
Once a pointer variable has been declared we can use the assignment operator to initialize the variable.
Example:
int quantity = 10;
int *p; /* declaration */
p=&quantity; /* initialization */
int *p = &quantity;
The only requirement here is that the variable quantity must be declared bef the initialization takes place.

SEMESTER I::Problem Solving in C Page 14


KUMAR NAGISETTI

2. Explain about address and indirection operators in C with example?


Accessing the address of a variable (&):
The actual location of a variable in the memory is system dependent and therefore, the address of a variable
is not known to us immediately. This can be done with the help of the operator & available in C. The operator &
immediately preceding a variable returns the address of the variable associated with it. For example, the statement.
p = &quantity;
would assign the address 1000 (the location of quantity ) to the variable p. The & operator can be remembered as
'address of.
Accessing a variable through its pointer (*):
Once a pointer has been assigned the address of a variable, to access the value of the variable using another
unary operator *(asterisk), usually known as the indirection operator. Another name for the indirection operator is
the dereferencing operator. Consider the following statements:
int quantity, *p, n;
quantity = 179;
p = &quantity;
n = *p;
In this case, *p returns the value of the variable quantity, because p is the address of quantity. The *can be
remembered as 'value at address'. Thus the value of n would be 179.

Program:
void main (){
int x=10, Output
int *ptr; Value of x is 10
ptr = &x; 10 is stored at addr 4104
printf("Value of x is %d\n\n", x); x value =10
printf("%d is stored at address %u\n", x, &x); Now x = 25
printf("x value =%d", *ptr),
*ptr = 25;
printf("\n Now x = %d\n", x);
}
Write short notes on pointer expressions and pointer Arithmetic?
Pointer expressions: Similar to other variables, pointer variables can also be used in expressions. For
example, if ptr1 and ptr2 are pointers, then the following statements are valid.
int num1 = 2, num2 = 3, sum=0, mul = 0,
int *ptr1, *ptr2;
ptr1 = &numl;
ptr2 = &num2;
sum = *ptr1 + *ptr2;
mul = sum * *ptr1;
Pointer Arithmetic: As a pointer holds the memory address of a variable, some arithmetic operations can be
performed with pointers.
C supports four arithmetic operators that can be used with pointer, such as
Addition +
Substraction -
Incrementation ++
Decrementation --
Pointers are variables. They are not integers, but they can be displayed as unsigned integers. The conversion
specifier for a pointer is added and subtracted. For example,
ptr + + causes the pointer to be incremented, but not by 1.
Ptr-- causes the pointer to be decremented, but not by 1.
SEMESTER I::Problem Solving in C Page 15
KUMAR NAGISETTI

The following program segment illustrates the pointer arithmetic.


The integer value would occupy bytes 2000 and 2001.
void main ()
{
int value, *ptr;
value = 120;
ptr = & value;
ptr ++;
printf("%u\n", ptr);
}
The above C program segment displays 2002.
The pointer ptr is originally assigned the value 2000. The incrimination, ptr ++ increments the number of bytes of
the storage class for the particular machine.
The general rule for pointer arithmetic is that pointer performs the operation in bytes of the appropriate storage
class.
Explain the call by address technique of passing parameters to functions?
When we pass addresses to a function, the parameters receiving the addresses should be pointers. The
process of calling a function using pointers to pass the addresses of variables is known as 'call by reference'. The
function which is called by 'reference' can change the value of the variable used in the call.
Program: Write a function using pointers to exchange the values stored in two locations in the memory.
#include <stdio.h>
void swap (int*, int*);
void main ()
{
int x, y;
x = 100;
y = 200;
Output
printf("Before swaping: x=%d y=%d\n\n", x, y);
Before swaping: x = 100 y = 200
swap (&x, &y);
After swaping: x = 200 y = 100
printf("After swaping: x=%d y=%d\n\n", x, y):
}
void swap (int *a, int *b)
{
int t;
t = *a;
*a = *b;
*b=t;
}
How are arrays related to pointers? (OR) How to create arrays using pointers? Explain.
POINTERS AND ARRAYS: When an array is declared, the compiler allocates a base address and sufficient
amount of storage to contain all the elements of the array in contiguous memory locations. The base address is the
location of the first element (index 0) of the array. Suppose we declare an array x as follows:
int x[5]={1, 2, 3, 4, 5);
Suppose the base address of x is 1000 and assuming that each integer requires two bytes, the five elements
will be stored as follows:

SEMESTER I::Problem Solving in C Page 16


KUMAR NAGISETTI

If we declare p as an integer pointer, then we can make the pointer p to point to the array x by the following
assignment :
int*p;
p = x;
This is equivalent to p = &x[0];
Now, we can access every value of x using p++ to move from one element to another.
A program to read and display an array of n integers.
#include <stdio.h>
void main()
{
int i, n;
int arr[10], *parr = arr; Output
printf("\n Enter the number of elements: "); Enter the number of elements: 5
scanf ("%d", &n); Enter the elements: 12345
printf("\n Enter the elements : "); The elements entered are: 12345
for (i=0; i<n; i++)
scanf("%d", (parr+i));
printf("\n The elements entered are: ");
for (i=0; i<n; i++)
printf("\t%d", *(parr+i));
}
Briefly explain array of pointers?
1. Array of integer pointers: Pointers may be arrayed like any other data type.
An array of pointers can be declared as
int *ptr[5];
The above statement declares an array of 5 pointers where each of the pointer points to an integer variable.
For example, look at the following code:
#include <stdio.h>
void main ()
{
int *ptr[3],i;
int a=10, b=20, c=30; Output
ptr[0]=&a; a, b, and c values are:
ptr[1]=&b; 10 20 30
ptr[2]=&c;
printf("a,b and c values are \n");
for (i=0; i<3; i++)
printf("%d\t", *ptr[i]);
}
2. Array of character pointers:
Now, consider an array of character pointers that is pointed to the strings.
char *ptr[3];
In the ptr array, each element is a character pointer. Initialize an array of characters with three strings can be
given as, char *ptr [3] = {"Rohan", "Raj", "Sree"};
Here ptr[0] is Rohan, ptr[1] is Raj and ptr[2] is sree. The memory layout of ptr can be given as shown in
figure below.

SEMESTER I::Problem Solving in C Page 17


KUMAR NAGISETTI

#include <stdio.h>
void main() { OUTPUT:
char *ptr[] = {"Rohan", "Raj", "Sree"}; Rohan
int i; Raj
for (i = 0; i < 3; i++) { Sree
printf("%s\n", ptr[i]);
}
}
Explain about passing an array to function using pointers?
An array can be passed to a function using pointers. For this, a function that excepts an array can declare the formal
parameter in either of the two following ways.
func(int arr[ ]); or func (int *arr);
When we pass the name of the array to a function, the address of the 0th element of the array is copied to the local
pointer variable in the function.
Program: A program to read and print an array of n numbers:
#include <stdio.h>
void read_array (int *arr, int n);
void print_array (int *arr, int n);
void main()
{
int a [10], n; OUTPUT:
printf("\n Enter the size of the array:"); Enter the size of the array: 5
scanf("%d", &n); Enter the array elements: 1 2 3 4 5
read_array (a, n); The array elements are: 1 2 3 4 5
print_array(a, n);
}
void read_array(int *arr, int n)
{
int i;
printf("\n Enter the array elements: ");
for (i=0; i<n; i++)
scanf("%d", &arr[i]);
}
void print_array (int *arr, int n)
{
int i;
printf("\n The array elements are: ");
for (i=0; i<n; i++)
printf("\t%d", arr[i]);
}
Write about drawbacks of pointers?
Some common errors encountered when using pointers.
1. Error un-initialized pointer: px is pointing to an unknown memory location.
Hence it will overwrite that location's contents and store 10 in it. Such a pointer is called a wild pointer. A
pointer which is not initialized with any address is called a wild pointer. It may contain any garbage address and
thus dereferencing a wild pointer can be dangerous.
int x, *px;
x = 10;
px = x;
ERROR: it should be px = &x;
SEMESTER I::Problem Solving in C Page 18
KUMAR NAGISETTI

2. Memory leak: Memory leakage occurs when memory is allocated but not released when it is no longer required.
This causes an application to unnecessarily consume memory thereby reducing the memory available for other
applications. Although in small programs it is not a big concern but when dealing with large projects, memory
leakage may result in slowing down the application or crashing the application when the computer memory
resource limits are reached.
3. Dangling pointer: Dangling pointers arise when an object is deleted or de-allocated, without modifying the
value of the pointer.
Dangling pointer problem occurs when the pointer still points to the same location in memory even though the
reference has been deleted and may now be used for other purpose.
Consider the following code which illustrates dangling pointer problem.
char *ptr1;
char *ptr2 = (char*) malloc (size of (char));
ptr1 = ptr2;
free (ptr2);
Now ptr1 becomes a dangling pointer.
4. Memory corruption: Memory corruption often occurs when due to programming errors, the contents of a
memory location gets modified unintentionally.
Memory corruption errors can be broadly classified into following categories.
i) Using un-initialized memory: An un-initialized memory contains garbage value.
ii) Using un-owned memory: A common programming mistake to use pointers for accessing and modifying
memory that is not owned by the program. This situation may arise when the pointer happens to be a null pointer or
a dangling pointer. Using such a pointer to write to a memory location is a serious programming flaw as it may lead
to crash another program or even the operating system.
iii) Using beyond allocated memory (buffer overflow): If the elements of the array are accessed in a loop, with
incorrect terminating condition, memory beyond the array bounds may be manipulated. Buffer overflow is a
common programming flaw exploited by computer viruses causing serious threat to computer security.
iv) Faulty de-allocation of memory: Memory leaks and freeing un-allocated memory can also result in memory
corruption.

SEMESTER I::Problem Solving in C Page 19

You might also like