0% found this document useful (0 votes)
32 views66 pages

Unit III Notes

Uploaded by

Dharshan
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)
32 views66 pages

Unit III Notes

Uploaded by

Dharshan
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/ 66

UNIT 3

FUNCTIONS AND POINTERS


Function Definition – Function Prototype, Function Call, Built-in Functions (String Functions,
Math Functions), Recursion Functions.
Pointers – Pointer Operators, Pointer Arithmetic, Arrays and Pointers, Array of Pointers,
Parameter Passing – Pass by Value, Pass by Reference.

C Functions
 A function in C is a set of statements that when called perform some specific task.
 It is the basic building block of a C program that provides modularity and code reus-
ability.
 The programming statements of a function are enclosed within { } braces, having
certain meanings and performing certain operations.
 They are also called subroutines or procedures in other languages.
 In this article, we will learn about
o Functions,
o Function Definition.
o Declaration,
o Arguments And
o Parameters,
o Return Values, And Many More.
Function Definition
 A function is a self-contained block or a sub program of one or more statement
that perform a special task when called.
 A function is often executed several times from several different places during a
single execution of the program.
Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
1. Function Declaration
2. Function Definition
3. Function Calls
1) 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 somewhere else in the program.
Syntax
return_type name_of_the_function (parameter_1, parameter_2);

 The parameter name is not mandatory while declaring functions.


1
 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.

2) 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).
 A C function is generally defined and declared in a single step because the function
definition always starts with the function declaration so we do not need to declare it
explicitly.
 The below example serves as both a function definition and a declaration.
return_type function_name (para1_type para1_name, para2_type
para2_name)
{
// body of the function
}

3) 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.
 In the below example, the first sum function is called and 10,30 are passed to the
sum function.

2
 After the function call sum of a and b is returned and control is also returned back
to the main function of the program.

Note: Function call is necessary to bring the program control to the function
definition. If not called, the function statements will not be executed.
Example of C Function
// C program to show function call and definition
#include <stdio.h>
// Function that takes two parameters a and b as inputs and returns their sum
int sum(int a, int b)
{
return a + b;
}
// Driver code
int main()
{
// Calling sum function and storing its value in add variable
int add = sum(10, 30);
printf("Sum is: %d", add);
return 0;
}
Output
Sum is: 40
 As we noticed, we have not used explicit function declaration.
 We simply defined and called the function.
Function Return Type
 Function return type tells what type of value is returned after all function is exe-
cuted.
 When we don’t want to return a value, we can use the void data type.
Example:
3
int func(parameter_1,parameter_2);

 The above function will return an integer value after running statements inside the
function.
Note: Only one value can be returned from a C function.
To return multiple values, we have to use pointers or structures.
Function Arguments
 Function Arguments (also known as Function Parameters) are the data that is
passed to a function.
Example:
int function_name(int var1, int var2);

Conditions of Return Types and Arguments (or) Types of Function according to


Arguments and Return Values:-
 In C programming language, functions can be called either with or without arguments
and might return values.
 They may or might not return values to the calling functions.
1. Function with arguments and with return value
2. Function with argument and with no return value
3. Function with no arguments and with return value
4. Function with no arguments and no return value
1. Function with arguments and return value
Syntax:
Function declaration : int function ( int );
Function call : function( x );
Function definition:
int function( int x )
{
statements;
return x;
}

Example:

// C code for function with arguments and return value


#include <stdio.h>
#include <string.h>

int function(int, int[]);

4
int main()
{
int i, a = 20;
int arr[5] = { 10, 20, 30, 40, 50 };

a = function(a, &arr[0]);

printf("value of a is %d\n", a);


for (i = 0; i < 5; i++) {
printf("value of arr[%d] is %d\n", i, arr[i]);
}

return 0;
}

int function(int a, int* arr)


{
int i;
a = a + 20;

arr[0] = arr[0] + 50;


arr[1] = arr[1] + 50;
arr[2] = arr[2] + 50;
arr[3] = arr[3] + 50;
arr[4] = arr[4] + 50;

return a;
}

Output
value of a is 40
value of arr[0] is 60
value of arr[1] is 70
value of arr[2] is 80
value of arr[3] is 90
value of arr[4] is 100

5
2. Function with arguments but no return value
 When a function has arguments, it receives any data from the calling function but it
returns no values.
 These are void functions with no return values.
Syntax:
Function declaration : void function ( int );
Function call : function( x );
Function definition:
void function( int x )
{
statements;
}

Example:

// C code for function with argument but no return value


#include <stdio.h>

void function(int, int[], char[]);

int main()
{
int a = 20;
int ar[5] = { 10, 20, 30, 40, 50 };

char str[30] = "geeksforgeeks";

// function call
function(a, &ar[0], &str[0]);

return 0;
}
void function(int a, int* ar, char* str)
{
int i;
printf("value of a is %d\n\n", a);

for (i = 0; i < 5; i++)

6
{
printf("value of ar[%d] is %d\n", i, ar[i]);
}

printf("\nvalue of str is %s\n", str);


}

Output
value of a is 20
value of ar[0] is 10
value of ar[1] is 20
value of ar[2] is 30
value of ar[3] is 40
value of ar[4] is 50
value of str is geeksforgeeks

3. Function with no argument and no return value


 When a function has no arguments, it does not receive any data from the calling
function.
 Similarly, when it does not return a value, the calling function does not receive any
data from the called function.
Syntax:
Function declaration : void function();
Function call : function();
Function definition :
void function()
{
statements;
}
Example:

// C code for function with no arguments and no return value


#include <stdio.h>

void value(void);

void main()
{

7
value();
}

void value(void)
{
float year = 1, period = 5, amount = 5000, inrate = 0.12;
float sum;
sum = amount;
while (year <= period)
{
sum = sum * (1 + inrate);
year = year + 1;
}
printf(" The total amount is :%f", sum);
}

Output
The total amount is :8811.708984

4. Function with no arguments but returns a value


 There could be occasions where we may need to design functions that may not
take any arguments but returns a value to the calling function.
 An example of this is getchar function which has no parameters but it returns an in-
teger and integer-type data that represents a character.
Syntax:
Function declaration : int function();
Function call : function();
Function definition :
int function()
{
statements;
return x;
}
Example:

// C code for function with no arguments but have return value


#include <math.h>
#include <stdio.h>

8
int sum();

int main()
{
int num;
num = sum();
printf("Sum of two given values = %d", num);
return 0;
}

int sum()
{
int a = 50, b = 80, sum;
sum = sqrt(a) + sqrt(b);
return sum;
}

Output
Sum of two given values = 16
How Does C Function Work?
 Working of the C function can be broken into the following steps as mentioned be-
low:
1. Declaring a function:
 Declaring a function is a step where we declare a function.
 Here we define the return types and parameters of the function.
2. Defining a function:
 A function is a group of statements that together perform a task.
3. Calling the function:
 Calling the function is a step where we call the function by passing the
arguments in the function.
4. Executing the function:
 Executing the function is a step where we can run all the statements in-
side the function to get the final result.
5. Returning a value:
 Returning a value is the step where the calculated value after the execu-
tion of the function is returned.
 Exiting the function is the final step where all the allocated memory to
the variables, functions, etc is destroyed before giving full control to the
main function.

9
Types of Functions
 There are two types of functions in C:
1. Library Functions
2. User Defined Functions

1. Library Function
 A library function is also referred to as a “built-in function”.
 A compiler package already exists that contains these functions, each of which
has a specific meaning and is included in the package.
 Built-in functions have the advantage of being directly usable without being de-
fined, whereas user-defined functions must be declared and defined before being
used.
For Example:
pow(), sqrt(), strcmp(), strcpy() etc.

Advantages of C library functions


 C Library functions are easy to use and optimized for better performance.
 C library functions save a lot of time i.e, function development time.
 C library functions are convenient as they always work.
Example:
// C program to implement the above approach
#include <math.h>
#include <stdio.h>

// Driver code
int main()
{
double Number;
Number = 49;

// Computing the square root with the help of predefined C library function
double squareRoot = sqrt(Number);

printf("The Square root of %.2lf = %.2lf", Number, squareRoot);


return 0;
}
Output
The Square root of 49.00 = 7.00

10
2. User Defined Function
 Functions that the programmer creates are known as User-Defined functions
or “tailor-made functions”.
 User-defined functions can be improved and modified according to the need of
the programmer.
 Whenever we write a function that is case-specific and is not defined in any
header file, we need to declare and define our own functions according to the
syntax.
Advantages of User-Defined Functions
 Changeable functions can be modified as per need.
 The Code of these functions is reusable in other programs.
 These functions are easy to understand, debug and maintain.
Example:
// C program to show user-defined functions
#include <stdio.h>

int sum(int a, int b)


{
return a + b;
}

// Driver code
int main()
{
int a = 30, b = 40;

// function call
int res = sum(a, b);

printf("Sum is: %d", res);


return 0;
}

Output
Sum is: 70

Passing Parameters to Functions


 The data passed when the function is being invoked is known as the Actual pa-
rameters.

11
 In the below program, 10 and 30 are known as actual parameters.
 Formal Parameters are the variable and the data type as mentioned in the func-
tion declaration.
 In the below program, a and b are known as formal parameters.

 We can pass arguments to the C function in two ways:


1. Pass by Value
2. Pass by Reference
1. Pass by Value
 Parameter passing in this method copies values from actual parameters into for-
mal function parameters.
 As a result, any changes made inside the functions do not reflect in the caller’s
parameters.
Example:
// C program to show use of call by value
#include <stdio.h>

void swap(int var1, int var2)


{
int temp = var1;
var1 = var2;
var2 = temp;
}

// Driver code
12
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",var1, var2);
swap(var1, var2);
printf("After swap Value of var1 and var2 is: %d, %d",var1, var2);
return 0;
}
Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 3, 2
2. Pass by Reference
 The caller’s actual parameters and the function’s actual parameters refer to the
same locations, so any changes made inside the function are reflected in the
caller’s actual parameters.
Example:
// C program to show use of call by Reference
#include <stdio.h>

void swap(int *var1, int *var2)


{
int temp = *var1;
*var1 = *var2;
*var2 = temp;
}

// Driver code
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",var1, var2);
swap(&var1, &var2);
printf("After swap Value of var1 and var2 is: %d, %d",var1, var2);
return 0;
}
Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 2, 3

13
Advantages of Functions in C
 Functions in C is a highly useful feature of C with many advantages as mentioned
below:
 The function can reduce the repetition of the same statements in the pro-
gram.
 The function makes code readable by providing modularity to our program.
 There is no fixed number of calling functions it can be called as many times
as you want.
 The function reduces the size of the program.
 Once the function is declared you can just use it without thinking about the
internal working of the function.
Disadvantages of Functions in C
 The following are the major disadvantages of functions in C:
 Cannot return multiple values.
 Memory and time overhead due to stack frame allocation and transfer of
program control.
Conclusion
 In this article, we discussed the following points about the function as mentioned
below:
 The function is the block of code that can be reused as many times as we
want inside a program.
 To use a function we need to call a function.
 Function declaration includes function_name, return type, and parameters.
 Function definition includes the body of the function.
 The function is of two types user-defined function and library function.
 In function, we can according to two types call by value and call by refer-
ence according to the values passed.

Questions on Functions in C
Q1. Define functions.
Answer:
Functions are the block of code that is executed every time they are called during
an execution of a program.
Q2. What is a forward declaration?
Answer:
Sometimes we define the function after its call to provide better readibliy. In such
cases, we declare function before the their defiinition and call. Such declaration are
called Forward Declaration.

14
Q3. What is the difference between function declaration and definition?
Answer:
The data like function name, return type, and the parameter is included in the func-
tion declaration whereas the definition is the body of the function. All these data are
shared with the compiler according to their corresponding steps.
Q4. What is the difference between function arguments and parameters?
Answer:
Function parameters are the values declared in a function declaration. Whereas,
function arguments are the values that are passed in the function during the func-
tion call.
Example:
int func(int x,int y);
func(10,20);
Here, int x and int y are parameters while, 10 and 20 are the arguments passed to
the function.
Difference between Argument and Parameter

Argument Parameter

When a function is called, the values The values which are defined at the time of the
that are passed during the call are function prototype or definition of the function
called as arguments. are called as parameters.

These are used in function call These are used in function header of the called
statement to send value from the calling function to receive the value from the
function to the receiving function. arguments.

During the time of call each argument is Parameters are local variables which are
always assigned to the parameter in the assigned value of the arguments when the
function definition. function is called.

They are also called Actual Parameters They are also called Formal Parameters

Example: Example:

int num = 20; int Call(int rnum)


Call(num) {

15
Argument Parameter

printf("the num is %d", rnum);


// num is argument }
// rnum is parameter

Q5. Can we return multiple values from a C Function?


Answer:
No, it is generally not possible to return multiple values from a function. But we can
either use pointers to static or heap memory locations to return multiple values or
we can put data in the structure and then return the structure.
Q6. What is the actual and formal parameter?
Answer:
Formal parameter: The variables declared in the function prototype is known as
Formal arguments or parameters.
Actual parameter: The values that are passed in the function are known as actual
arguments or parameters.

Function Prototype in C
 The C function prototype is a statement that tells the compiler about the function’s
name, its return type, numbers and data types of its parameters.
 By using this information, the compiler cross-checks function parameters and their
data type with function definition and function call.
 Function prototype works like a function declaration where it is necessary where the
function reference or call is present before the function definition but optional if the
function definition is present before the function call in the program.
Syntax
return_type function_name(parameter_list);

where,
 return_type:
 It is the data type of the value that the function returns.
 It can be any data type int, float, void, etc.
 If the function does not return anything, void is used as the return
type.
 function_name:
 It is the identifier of the function.

16
 Use appropriate names for the functions that specify the purpose
of the function.
 parameter_list:
 It is the list of parameters that a function expects in parentheses.
 A parameter consists of its data type and name.
 If we don’t want to pass any parameter, we can leave the paren-
theses empty.
For example,
int func(int, char, char *, float);
Example:
Program to illustrate the Function Prototype
// C program to illustrate the function prototype
#include <stdio.h>
// Function prototype
float calculateRectangleArea(float length, float width);

int main()
{
float length = 5.0;
float width = 3.0;
// Function call
float area = calculateRectangleArea(length, width);

printf("The area of the rectangle is: %.2f\n", area);

return 0;
}
// Function definition
float calculateRectangleArea(float length, float width)
{
return length * width;
}
Output
The area of the rectangle is: 15.00
What if the function prototype is not specified?
 If we ignore the function prototype, a program may compile with a warning, it may
give errors and may work properly.
 But sometimes, it will give strange output and it is very hard to find such program-
ming mistakes.

17
Example: Program without a function prototype
 The below code opens a file specified by the command-line argument, checks if the
file exists, and then closes the file.
 The prototype of strerror function is not included in the code.
// C code to check if a file exists or not.
// Prototype of strerror function is not included in the code.
#include <errno.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
FILE* fp;
fp = fopen(argv[1], "r");
if (fp == NULL)
{
fprintf(stderr, "%s\n", strerror(errno));
return errno;
}
printf("file exist\n");
fclose(fp);
return 0;
}
Let us provide a filename, which does not exist in a file system, and check the output of
the program on x86_64 architecture.
Output
[narendra@/media/partition/GFG]$ ./file_existence hello.c
Segmentation fault (core dumped)
Explanation
The above program checks the existence of a file, provided from the command line, if a
given file exists, then the program prints “file exists”, otherwise it prints an appropriate er-
ror message.
Why did this program crash, instead it should show an appropriate error message. This
program will work fine on x86 architecture but will crash on x86_64 architecture. Let us see
what was wrong with the code. Carefully go through the program, deliberately I haven’t in-
cluded the prototype of the “strerror()” function. This function returns a “pointer to the char-
acter”, which will print an error message which depends on the errno passed to this func-
tion.
Note that x86 architecture is an ILP-32 model, which means integers, pointers, and long
are 32-bit wide, that’s why the program will work correctly on this architecture. But x86_64
is the LP-64 model, which means long and pointers are 64-bit wide. In C language, when

18
we don’t provide a prototype of a function, the compiler assumes that the function returns
an integer. In our example, we haven’t included the “string.h” header file (strerror’s proto-
type is declared in this file), that’s why the compiler assumed that the function returns an
integer. But its return type is a pointer to a character.
In x86_64, pointers are 64-bit wide and integers are 32-bit wide, that’s why while returning
from a function, the returned address gets truncated (i.e. 32-bit wide address, which is the
size of integer on x86_64) which is invalid and when we try to dereference this address,
the result is a segmentation fault.
Now include the “string.h” header file and check the output, the program will work
correctly and gives the following output.
[narendra@/media/partition/GFG]$ ./file_existence hello.c
No such file or directory
Consider one more example
This code demonstrates the process of dynamic memory allocation using the malloc func-
tion, but the prototype of the malloc function is not included.
// This code dynamically allocates memory for an integer using the malloc function but
prototype of malloc function is not included in the code
#include <stdio.h>
int main(void)
{
int* p = malloc(sizeof(int));
if (p == NULL)
{
perror("malloc()");
return -1;
}
*p = 10;
free(p);

return 0;
}
Explanation
The above code will work fine on the IA-32 model but will fail on the IA-64 model. The rea-
son for the failure of this code is we haven’t included a prototype of the malloc() function
and the returned value is truncated in the IA-64 model.
Question on Function Prototype
Q1. Difference between Function Declaration and Function Prototype
Answer:
Following are some differences between Function and Function Prototype:

19
Function Declaration Function Prototype

The function prototype tells the compiler


Function Declaration is used to tell the
about the existence and signature of the
existence of a function.
function.

A function declaration is valid even with A function prototype is a function


only function name and return delcaration that provides the function’s
type. name, return type, and parameter list
without including the function body.

Typically used in header files to declare Used to declare functions before their actual
functions. definitions.

Syntax: Syntax:
return_type function_name(); return_type function_name(parameter_list);

String Functions Overview


 Strings are an array of characters that terminate with a null character '\0'.
 The difference between a character array and a string is that, unlike the character ar-
ray, the string ends with a null character.
 There are various built-in string functions in the C programming language.
Introduction to C String Functions
 We're often required to modify the strings and perform several operations on them
according to our needs.
 If we want to get the length of the string, we could run a loop and calculate its length,
but it is not the best way in case of complex problems.
 Hence, string functions are used to make our code efficient and straightforward as
they are pre-written so we can use them directly.
String Handling Functions
 The string handling functions are defined in the header file string.h.
 This header file must be included in the C program to use the string handling func-
tions.
String Declaration
 There are two ways to declare strings in C:
1. The following example will create a string as "Scaler" where the last character
must always be a null character.

20
The size mentioned within the brackets is the maximum number of characters a
string could hold, and it is mandatory to give the size of a string if we are not
initializing it at the time of declaration.
char company[7] = {'S', 'C', 'A', 'L', 'E', 'R' , '\0'};
2. In this method, we do not need to put the null character at the end of the string
constant.
The compiler automatically inserts the null character at the end of the string.
char company[] = "SCALER";
String Functions
The following are the string functions in C:

Function Description

strlen() It returns the string's length.

It returns the specified value if the value specified is less than the string
strnlen()
length, otherwise the string length.

strcmp() It compares two strings and returns 0 if the strings are the same.

strncmp() It compares two strings only to n characters.

strcat() It concatenates two strings and returns the concatenated string.

strncat() It concatenates n characters of one string to another string.

strcpy() It copies one string into another.

strncpy() It copies the first n characters of one string into another.

strchr() It finds out the first occurrence of a given character in a string.

strrchr() It finds out the last occurrence of a given character in a string.

strstr() It finds out the first occurrence of a given string in a string.

It finds out the first occurrence of a given string in a string where the search
strnstr()
is limited to n characters.

strcasecmp() It compares two strings without sensitivity to the case.

It compares n characters of one string to another without sensitivity to the


strncasecmp()
case.

strtok() This function breaks a string into a series of tokens based on a delimiter

strlwr() This function converts a string to lowercase

strupr() This function converts a string to Uppercase

strdup() This function duplicates a string.

Strrev() Is used to reverse the string

strset( ) This function sets all the characters in a string to given character.

21
Function Description

strnset() This function sets portion of characters in a string to given character

Examples of String Functions in C


Let's look at an example to understand how string functions work in C.
1) String Length - strlen()
 This function can be used to find a string length.
 It takes a string (character array or character pointer) as input and writes the length
of that string without including the end character '\0'.
Syntax
size_t strlen(const char *str)
size_t represents long unsigned int.
Program Code
#include <stdio.h>
#include <string.h>
int main()
{
char string1[20] = "ScalerAcademy";
printf("Length of string string1: %ld", strlen(string1));
return 0;
}
Output
Length of string string1: 13
2) Length of n String - strnlen()
 strnlen() take a string and a positive integer maxlen as input and return the length of
the string if maxlen is greater than the size of the string otherwise, always return
maxlen which means it only counts the characters till str[maxlen -1].

Syntax
size_t strnlen(const char *str, size_t maxlen)
size_t represents long unsigned int.
Program Code
#include <stdio.h>
#include <string.h>
int main()
{
char str[20] = "ScalerAcademy";
printf("Length of str when maxlen is 25: %ld \n", strnlen(str, 25));
printf("Length of strwhen maxlen is 5: %ld", strnlen(str, 5));
22
}
Output
Length of str when maxlen is 25: 13.
Length of str when maxlen is 5: 5
3) String Compare - strcmp()
 This function is used to compare two strings.
 strcmp() takes two strings as input, then compares them, and returns an integer
based on the following condition:
Expression Returns

string 1 > string 2 Positive integer

string 1 < string 2 Negative

string 1 = string 2 Zero


Syntax
int strcmp(const char *str1, const char *str2)
Program Code
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "ScalerAcademy"; // string1
char s2[20] = "ScalerAcademy.COM"; // string2
// comparing both the strings
if (strcmp(s1, s2) == 0)
{
printf("string 1 and string 2 are equal");
}
else
{
printf("string 1 and 2 are different");
}
}
Output
string 1 and 2 are different

23
4) String of n Compare - strncmp()
 It compares only the first n characters of both the strings and returns an
integer value accordingly:

Expression Returns

string 1(first n characters) > string 2(first n characters) Positive integer

string 1(first n characters) < string 2(first n characters) Negative

string 1(first n characters) = string 2(first n characters) Zero

Syntax
int strncmp(const char *str1, const char *str2, size_t n)
size_t is for long unsigned int.
Program Code
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "ScalerAcademy";
char s2[20] = "ScalerAcademy.COM";
/* it only compares first 5 characters of both strings*/
if (strncmp(s1, s2, 5) == 0)
{
printf("string 1 and string 2 are equal");
}
else
{
printf("string 1 and 2 are different");
}
}
Output
string 1 and string 2 are equal
5) String Concatenates - strcat()
 It takes two strings as input and concatenates the second string to the first string,
which means it will attach the second string to the end of the first string and save the
concatenated string to the first string.
 The size of the first string should be large enough to save the result.
Syntax
char *strcat(char *str1, char *str2)
Program Code
#include <stdio.h>
24
#include <string.h>
int main()
{
char string1[10] = "Hello";
char string2[10] = "World";
strcat(string1, string2);
printf("Output string after concatenation: %s", string1);
}
Output
Output string after concatenation: HelloWorld
(OR)
 The strcat() function in C is used for string concatenation. It will append a copy of the
source string to the end of the destination string.
Syntax
char* strcat(char* dest, const char* src);
The terminating character at the end of dest is replaced by the first character of src.
Parameters
 dest: Destination string
 src: Source string
Return value
 The strcat() function returns a pointer to the dest string.
Example
// C Program to illustrate the strcat function
#include <stdio.h>

int main()
{
char dest[50] = "This is an";
char src[50] = " example";
printf("dest Before: %s\n", dest);
// concatenating src at the end of dest
strcat(dest, src);
printf("dest After: %s", dest);
return 0;
}
Output
dest Before: This is an
dest After: This is an example

25
6) String of n Concatenates - strncat()
 It takes two strings as input and attaches only the first n characters of the second
string to the end of the first string.
 This function lexicographically compares the first n characters from the two null-ter-
minated strings and returns an integer based on the outcome.
Syntax
char *strncat(char *str1, char *str2, int n)
Program Code
#include <stdio.h>
#include <string.h>
int main ()
{
char string1[10] = "Hello";
char string2[10] = "World";
strncat(string1,string2, 3);
printf("Concatenation using strncat: %s", string1);
}
Output
Concatenation using strncat: HelloWor
7) String Copy - strcpy()
 It takes two strings as input and overwrites the data of the second string into the first
string, i.e., it copies the data of the second string to the first string.

Syntax
char *strcpy( char *str1, char *str2)
Program Code
#include <stdio.h>
#include <string.h>
int main()
{
char s1[35] = "string 1"; // string1
char s2[35] = "I'll be copied to string 1."; // string2
strcpy(s1, s2); // copying string2 to string1
printf("String s1 is: %s", s1); // printing string1
}
Output
String s1 is: I'll be copied to string 1.

26
8) String of n Copy - strncpy()
 It takes two strings as input and overwrites the data of the first string by the second
string based on specific conditions:
 If the length of string2 is greater than n, it copies only the first n characters of string2
to string1; otherwise, it copies the entire string2 to string1.
Syntax
char *strncpy( char *str1, char *str2, size_t n)
size_t is long unsigned int and n is an integer.
Program Code
#include <stdio.h>
#include <string.h>
int main()
{
char string1[30] = "string 1";
char string2[40] = "Only 12 characters will be copied.";
strncpy(string1, string2, 12);
printf("String s1 is: %s", string1);
}
Output
String s1 is: Only 12 char
9) String Character/String First Character - strchr()
 It takes a string and a character as input and finds out the first occurrence of the
given character in that string.
 It will return the pointer to the first occurrence of that character; if found otherwise,
return Null.
Syntax
char *strchr(char *str, int ch)
Program Code 1
 When the character is present in the given string
#include <stdio.h>
#include <string.h>
int main()
{
char string1[30] = "I love to write.";
printf("%s", strchr(string1, 'w'));
}
Output
write.
Program code 2

27
 When the character is not present in the given string Notice the character 'z' is not
present in the provided string. In such a case, it returns a null value.
#include <stdio.h>
#include <string.h>
int main()
{
char string1[30] = "I love to write blogs.";
printf("%s", strrchr(string1, 'z'));
}
Output
(null)
10) String of Last Character - strrchr()
 It takes a string and a character as input and finds out the last occurrence of a given
character in that string.
 It will return the pointer to the last occurrence of that character if found otherwise, re-
turn Null.

Syntax
char *strrchr(char *str, int ch)
Program Code 1
#include <stdio.h>
#include <string.h>
int main()
{
char string1[30] = "I love to write blogs.";
printf("%s", strrchr(string1, 'w'));
}
Output
write blogs.
Program Code 2
 When the character is not present in the given string Notice the character 'z' is not
present in the provided string. In such a case, it returns a null value.
#include <stdio.h>
#include <string.h>
int main()
{
char string1[30] = "I love to write blogs.";
printf("%s", strrchr(string1, 'z'));
}

28
Output
(null)
11) String of First String - strstr()
 It takes two strings as input and finds out the first occurrence of the second string in
the first string.
 It will return a pointer that points to the start of the first occurrence of the second
string in the first string and a Null if the second string is not present in the first string.
Syntax
char *strstr(char *str, char *srch_term)
Program Code
#include <stdio.h>
#include <string.h>
int main()
{
char string1[70] = "You are reading string functions.";
printf("Output string is: %s", strstr(string1, "string"));
}
Output
Output string is: string functions.
12) String Case Compare - strcasecmp()
 It takes two strings as input and compares them irrespective of their case sensitivity

If Returns

str1 < str2 Less than 0

str1 = str2 (ignoring case) 0

str1 > str2 Greater than 0

Syntax
strcasecmp(str1, str2)
.Program Code
#include <stdio.h>
#include <string.h>
int main ()
{
char string1[70] = "STRING";
char string2[70]= "string";
int result;
result = strcasecmp(string1, string2);
//checking the result using conditional statements.
if (result == 0)

29
printf("Strings are equal.\n");
else if (result < 0)
printf("\"%s\" is less than \"%s\".\n", string1, string2);
else
printf("\"%s\" is greater than \"%s\".\n", string1, string2);
}
Output
Strings are equal.

13) String Case n Compare - strncasecmp()


 It takes two strings as input and compares them till n characters irrespective of their
case sensitivity.
Syntax
strncasecmp(str1, str2, n)
Program Code
#include <stdio.h>
#include <string.h>
int main()
{
char string1[70] = "STRING";
char string2[70] = "steing";
int result;
result = strncasecmp(string1, string2, 3);
//checking the result using conditional statements.
if (result == 0)
printf("Strings are equal.\n");
else if (result < 0)
printf("\"%s\" is less than \"%s\".\n", string1, string2);
else
printf("\"%s\" is greater than \"%s\".\n", string1, string2);
}
Output
"STRING" is greater than "steing".
14) String Token Break: strtok()
 This function breaks a string into a series of tokens based on a delimiter.
Example:
#include <stdio.h>
#include <string.h>
int main() {

30
char sentence[] = "This is a sample sentence";
char *token = strtok(sentence, " ");
while (token != NULL) {
printf("strtok(): %s\n", token);
token = strtok(NULL, " ");
}
return 0;
}
Output:
strtok(): This
strtok(): is
strtok(): a
strtok(): sample
strtok(): sentence
15) Lowercase String: strlwr()
 It takes a string as input and converts all the letters in the string to lowercase.
Syntax
char *strlwr(char *str);
Example
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
// Convert string to lowercase
strlwr(str);
printf("Lowercase string: %s\n", str);
return 0;
}
Output:
Lowercase string: hello, world!
16) Uppercase String: strupr()
 It takes a string as input and converts all the letters in the string to uppercase.
Syntax
char *strupr(char *str);
Example Code:
#include <stdio.h>
#include <string.h>

31
int main()
{
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
// Convert string to uppercase
strupr(str);
printf("Uppercase string: %s\n", str);
return 0;
}
Output:
Uppercase string: HELLO, WORLD!
17) Duplicate String: strdup()
 This function duplicates a string.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char original[] = "Original String";
char *duplicate = strdup(original);
printf("strdup(): %s\n", duplicate);
return 0;
}
Output:
strdup(): Original String
18) String Reverse - Strrev():
 It is used to reverse a given string.
 It takes a string as an argument and returns a pointer to the reversed string.
Syntax
char *strrev(char *str);
Example
#include <stdio.h>
#include <string.h>
int main()
{
char str[40]; // declare the size of character string
printf(" \n Enter a string to be reversed: ");
scanf("%s", str);
// use strrev() function to reverse a string
printf(" \n After the reverse of a string: %s ", strrev(str));

32
return 0;
}
Output:
Enter a string to be reversed: prepbytes
Áfter the reverse of a String: setybperp
19) strset() function in C:
 strset( ) function sets all the characters in a string to given character.
 strset( ) function is non-standard function which may not available in standard library
in C.
Syntax
char *strset(char *string, int c);
Example
 In this program, all characters of the string “Test String” is set to “#” using strset( )
function and output is displayed as “###########”.
#include<stdio.h>
#include<string.h>
int main()
{
char str[20] = "Test String";
printf("Original string is : %s", str);
printf("Test string after strset() : %s",strset(str,'#'));
printf("After string set: %s",str);
return 0;
}
Output:

Original string is : Test String


Test string after strset() : ###########

20) strnset() function in C:


 strnset( ) function sets portion of characters in a string to given character.
 strnset( ) function is non standard function which may not available in standard library
in C.
Syntax
char *strnset(char *string, int c);
Example
 In this program, first 4 characters of the string “Test String” is set to “#” using strnset(
) function and output is displayed as “#### String”.
#include<stdio.h>
#include<string.h>

33
int main()
{
char str[20] = "Test String";
printf("Original string is : %s", str);
printf("Test string after string n set" \ " : %s", strnset(str,'#',4));
printf("After string n set : %s", str);
return 0;
}
Output:

Original string is : Test String


Test string after string set : #### String

Math Functions
 The math.h header defines various C mathematical functions and one macro.
 All the functions available in this library take double as an argument and return dou-
ble as the result.
 Let us discuss some important C math functions one by one.
C Math Functions
1) double ceil (double x)
 The C library function double ceil (double x) returns the smallest integer value
greater than or equal to x.
Syntax
double ceil(double x);
Example
// C code to illustrate the use of ceil function.
#include <math.h>
#include <stdio.h>
int main()
{
float val1, val2, val3, val4;
val1 = 1.6;
val2 = 1.2;
val3 = -2.8;
val4 = -2.3;
printf("value1 = %.1lf\n", ceil(val1));
printf("value2 = %.1lf\n", ceil(val2));
printf("value3 = %.1lf\n", ceil(val3));
printf("value4 = %.1lf\n", ceil(val4));
return (0);
34
}
Output
value1 = 2.0
value2 = 2.0
value3 = -2.0
value4 = -2.0
2) double floor(double x)
 The C library function double floor(double x) returns the largest integer value less
than or equal to x.
Syntax
double floor(double x);
Example
// C code to illustrate the use of floor function
#include <math.h>
#include <stdio.h>
int main()
{
float val1, val2, val3, val4;
val1 = 1.6;
val2 = 1.2;
val3 = -2.8;
val4 = -2.3;
printf("Value1 = %.1lf\n", floor(val1));
printf("Value2 = %.1lf\n", floor(val2));
printf("Value3 = %.1lf\n", floor(val3));
printf("Value4 = %.1lf\n", floor(val4));
return (0);
}
Output
Value1 = 1.0
Value2 = 1.0
Value3 = -3.0
Value4 = -3.0
3) double fabs(double x)
 The C library function double fabs(double x) returns the absolute value of x.
Syntax
double fabs(double x)
Example
// C code to illustrate the use of fabs function

35
#include <math.h>
#include <stdio.h>
int main()
{
int a, b;
a = 1234;
b = -344;
printf("The absolute value of %d is %lf\n", a, fabs(a));
printf("The absolute value of %d is %lf\n", b, fabs(b));
return (0);
}
Output
The absolute value of 1234 is 1234.000000
The absolute value of -344 is 344.000000
4) double log(double x)
 The C library function double log(double x) returns the natural logarithm (base-e log-
arithm) of x.
Syntax
double log(double x)
Example
// C code to illustrate the use of log function
#include <math.h>
#include <stdio.h>
int main()
{
double x, ret;
x = 2.7;
/* finding log(2.7) */
ret = log(x);
printf("log(%lf) = %lf", x, ret);
return (0);
}
Output
log(2.700000) = 0.993252
5) double log10(double x)
 The C library function double log10(double x) returns the common logarithm (base-10
logarithm) of x.
Syntax
double log10(double x);

36
Example
// C code to illustrate the use of log10 function
#include <math.h>
#include <stdio.h>
int main()
{
double x, ret;
x = 10000;
/* finding value of log1010000 */
ret = log10(x);
printf("log10(%lf) = %lf\n", x, ret);
return (0);
}
Output
log10(10000.000000) = 4.000000
6) double fmod(double x, double y)
 The C library function double fmod(double x, double y) returns the remainder of x di-
vided by y.
Syntax
double fmod(double x, double y)
Example
// C code to illustrate the use of fmod function
#include <math.h>
#include <stdio.h>
int main()
{
float a, b;
int c;
a = 8.2;
b = 5.7;
c = 3;
printf("Remainder of %f / %d is %lf\n", a, c, fmod(a, c));
printf("Remainder of %f / %f is %lf\n", a, b, fmod(a, b));
return (0);
}
Output
Remainder of 8.200000 / 3 is 2.200000
Remainder of 8.200000 / 5.700000 is 2.500000
7) double sqrt(double x)

37
 The C library function double sqrt(double x) returns the square root of x.
Syntax
double sqrt(double x);
Example
// C code to illustrate the use of sqrt function
#include <math.h>
#include <stdio.h>
int main()
{
printf("Square root of %lf is %lf\n", 225.0, sqrt(225.0));
printf("Square root of %lf is %lf\n", 300.0, sqrt(300.0));
return (0);
}
Output
Square root of 225.000000 is 15.000000
Square root of 300.000000 is 17.320508
8) double pow(double x, double y)
 The C library function double pow(double x, double y) returns x raised to the power of
y i.e. xy.
Syntax
double pow(double x, double y);
Example
// C code to illustrate the use of pow function
#include <math.h>
#include <stdio.h>
int main()
{
printf("Value 8.0 ^ 3 = %lf\n", pow(8.0, 3));
printf("Value 3.05 ^ 1.98 = %lf", pow(3.05, 1.98));
return (0);
}
Output
Value 8.0 ^ 3 = 512.000000
Value 3.05 ^ 1.98 = 9.097324
9) double modf(double x, double *integer)
 The C library function double modf(double x, double *integer) returns the fraction
component (part after the decimal), and sets integer to the integer component.
Syntax
double modf(double x, double *integer)

38
Example
// C code to illustrate the use of modf function
#include <math.h>
#include <stdio.h>
int main()
{
double x, fractpart, intpart;
x = 8.123456;
fractpart = modf(x, &intpart);
printf("Integral part = %lf\n", intpart);
printf("Fraction Part = %lf \n", fractpart);
return (0);
}
Output
Integral part = 8.000000
Fraction Part = 0.123456
10) double exp(double x)
 The C library function double exp(double x) returns the value of e raised to the x th
power.
Syntax
double exp(double x);
Example
// C code to illustrate the use of exp function
#include <math.h>
#include <stdio.h>
int main()
{
double x = 0;
printf("The exponential value of %lf is %lf\n", x, exp(x));
printf("The exponential value of %lf is %lf\n", x + 1, exp(x + 1));
printf("The exponential value of %lf is %lf\n", x + 2, exp(x + 2));
return (0);
}
Output
The exponential value of 0.000000 is 1.000000
The exponential value of 1.000000 is 2.718282
The exponential value of 2.000000 is 7.389056

39
Recursion in C
 Recursion is the process which comes into existence when a function calls a copy of
itself to work on a smaller problem.
 Any function which calls itself is called recursive function, and such function calls are
called recursive calls.
 Recursion involves several numbers of recursive calls.
 However, it is important to impose a termination condition of recursion.
 Recursion code is shorter than iterative code however it is difficult to understand.
 Recursion cannot be applied to all the problem, but it is more useful for the tasks that
can be defined in terms of similar subtasks.
 For Example, recursion may be applied to sorting, searching, and traversal problems.
 Generally, iterative solutions are more efficient than recursion since function call is
always overhead.
 Any problem that can be solved recursively, can also be solved iteratively.
 However, some problems are best suited to be solved by the recursion,
 for example, tower of Hanoi, Fibonacci series, factorial finding, etc.
In the following example, recursion is used to calculate the factorial of a number.
#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)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{

40
return n*fact(n-1);
}
}
Output
Enter the number whose factorial you want to calculate?5
factorial = 120
We can understand the above program of the recursive method call by the figure
given below:

Recursive Function
 A recursive function performs the tasks by dividing it into the subtasks.
 There is a termination condition defined in the function which is satisfied by some
specific subtask.
 After this, the recursion stops and the final result is returned from the function.
 The case at which the function doesn't recur is called the base case whereas the in-
stances where the function keeps calling itself to perform a subtask, is called the re-
cursive case.
 All the recursive functions can be written using this format.
Pseudocode for writing any recursive function is given below.
if (test_for_base)
{
return some_value;
}
else if (test_for_another_base)
{
return some_another_value;
}
else
41
{
// Statements;
recursive call;
}
Example of recursion in C
Let's see an example to find the nth term of the Fibonacci series.
#include<stdio.h>
int fibonacci(int);
void main ()
{
int n,f;
printf("Enter the value of n?");
scanf("%d",&n);
f = fibonacci(n);
printf("%d",f);
}
int fibonacci (int n)
{
if (n==0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return fibonacci(n-1)+fibonacci(n-2);
}
}
Output
Enter the value of n?12
144
Memory allocation of Recursive method
 Each recursive call creates a new copy of that method in the memory.
 Once some data is returned by the method, the copy is removed from the memory.
 Since all the variables and other stuff declared inside function get stored in the stack,
therefore a separate stack is maintained at each recursive call.

42
 Once the value is returned from the corresponding function, the stack gets destroyed.
 Recursion involves so much complexity in resolving and tracking the values at each
recursive call.
 Therefore we need to maintain the stack and track the values of the variables defined
in the stack.
Let us consider the following example to understand the memory allocation of the recursive
functions.
int display (int n)
{
if(n == 0)
return 0; // terminating condition
else
{
printf("%d",n);
return display(n-1); // recursive call
}
}
Explanation
 Let us examine this recursive function for n = 4.
 First, all the stacks are maintained which prints the corresponding value of n until n
becomes 0, Once the termination condition is reached, the stacks get destroyed one
by one by returning 0 to its calling stack.
 Consider the following image for more information regarding the stack trace for the
recursive functions.

43
44
UNIT 3 – POINTERS
Pointers – Pointer Operators, Pointer Arithmetic, Arrays and Pointers, Array of Pointers,
Parameter Passing – Pass by Value, Pass by Reference.

C Pointers
 Pointers are one of the core components of the C programming language.
 A pointer can be used to store the memory address of other variables, functions,
or even other pointers.
 The use of pointers allows low-level memory access, dynamic memory allocation,
and many other functionality in C.
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 point-
ers.
 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:
1. Pointer Declaration
2. Pointer Initialization
3. 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;

45
 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 declara-
tion.

46
Dereferencing a Pointer in C
C Pointer Example
// C program to illustrate Pointers
#include <stdio.h>
void geeks()
{
int var = 10;
// declare pointer variable
int* ptr;
// note that data type of ptr and var must be same
ptr = &var;
// assign the address of a variable to a pointer
printf("Value at ptr = %p \n", ptr);
printf("Value at var = %d \n", var);
printf("Value at *ptr = %d \n", *ptr);
}
// Driver program
int main()
{
geeks();
return 0;
}
Output
Value at ptr = 0x7fff1038675c
Value at var = 10
Value at *ptr = 10
Types of Pointers in C
 Pointers in C can be classified into many different types based on the parameter on
which we are defining their types.
47
 If we consider the type of variable stored in the memory location pointed by the
pointer, then the pointers can be classified into the following types:
1. Integer Pointers 6. NULL Pointer

48
2. Array Pointer 7. Void Pointer
3. Structure Pointer 8. Wild Pointers
4. Function Pointers 9. Constant Pointers
5. Double Pointers 10. Pointer to Constant
1. Integer Pointers
 As the name suggests, these are the pointers that point to the integer values.
Syntax
int *ptr;
 These pointers are pronounced as Pointer to Integer.
 Similarly, a pointer can point to any primitive data type.
 It can point also point to derived data types such as arrays and user-defined data types
such as structures.
2. Array Pointer
 Pointers and Array are closely related to each other.
 Even the array name is the pointer to its first element.
 They are also known as Pointer to Arrays.
 We can create a pointer to an array using the given syntax.
Syntax
char *ptr = &array_name;

 Pointer to Arrays exhibits some interesting properties which we discussed later in this arti-
cle.
 Example Program:
#include<stdio.h>
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;
printf("%p\n", ptr);
return 0;
}
 In this program, we have a pointer ptr that points to the 0th element of the array.
 Similarly, we can also declare a pointer that can point to whole array instead of only one
element of the array.
 This pointer is useful when talking about multidimensional arrays.
Syntax:
data_type (*var_name)[size_of_array];

49
 Explanation of above example program:
int (*ptr)[10];
 Here ptr is pointer that can point to an array of 10 integers.
 Since subscript have higher precedence than indirection, it is necessary to enclose the in-
direction operator and pointer name inside parentheses.
 Here the type of ptr is ‘pointer to an array of 10 integers’.
Note :
 The pointer that points to the 0 th element of array and the pointer that points to
the whole array are totally different.

3. Structure Pointer
 The pointer pointing to the structure type is called Structure Pointer or Pointer to Structure.
 It can be declared in the same way as we declare the other primitive data types.
Syntax
struct struct_name *ptr;
 In C, structure pointers are used in data structures such as linked lists, trees, etc.
4. Function Pointers
 Function pointers point to the functions.
 They are different from the rest of the pointers in the sense that instead of pointing to the
data, they point to the code.
 Let’s consider a function prototype – int func (int, char), the function pointer for this func-
tion will be
Syntax
int (*ptr)(int, char);

Note:
 The syntax of the function pointers changes according to the function prototype.

5. Double Pointers
 In C language, we can define a pointer that stores the memory address of another pointer.
 Such pointers are called double-pointers or pointers-to-pointer.
 Instead of pointing to a data value, they point to another pointer.
Syntax
datatype ** pointer_name;
Dereferencing Double Pointer

50
*pointer_name; // get the address stored in the inner level pointer
**pointer_name; // get the value pointed by inner level pointer
Note: In C, we can create multi-level pointers with any number of levels such as –
***ptr3, ****ptr4, ******ptr5 and so on.

6. NULL Pointer
 The Null Pointers are those pointers that do not point to any memory location.
 They can be created by assigning a NULL value to the pointer.
 A pointer of any type can be assigned the NULL value.
Syntax
data_type *pointer_name = NULL;
or
pointer_name = NULL
 It is said to be good practice to assign NULL to the pointers currently not in use.
7. Void Pointer
 The Void pointers in C are the pointers of type void.
 It means that they do not have any associated data type.
 They are also called generic pointers as they can point to any type and can be type-
casted to any type.
Syntax
void * pointer_name;

 One of the main properties of void pointers is that they cannot be dereferenced.
8. Wild Pointers
 The Wild Pointers are pointers that have not been initialized with something yet.
 These types of C-pointers can cause problems in our programs and can eventually cause
them to crash.
 Example
int *ptr;
char *str;

9. Constant Pointers
 In constant pointers, the memory address stored inside the pointer is constant and cannot
be modified once it is defined.
 It will always point to the same memory address.
Syntax

51
data_type * const pointer_name;

10. Pointer to Constant


 The pointers pointing to a constant value that cannot be modified are called pointers to a
constant.
 Here we can only access the data pointed by the pointer, but cannot modify it.
 Although, we can change the address stored in the pointer to constant.
Syntax
const data_type * pointer_name;

Pointer Operators in C
There are two types of pointer operators. They are
1. Address operator(&)
2. Indirection operator(*)
1) Address Operator:
It is used to get the address of the given variable. Consider the following,
Example:
int a = 10, *ptr;
ptr = &a;
Here, &a gives us the address of the variable a and the same is address to pointer
variable ptr. Address operator is also known as reference operator.

2) Indirection operator:
It is used to get the value stored in an address. Consider the following,
Example:
int a = 10, b, *ptr;
ptr = &a; // referencing(&a)
b = *ptr; // dereferencing(*ptr)

Here, ptr has the address of the variable a. On dereferencing the pointer ptr, we will get the value
stored at the address of a.
Example C program on pointer operators
#include <stdio.h>
int main()
{
int a = 10, b, *ptr;

52
ptr = &a; // referencing (&a)
b = *ptr; // dereferencing (*ptr)
printf("Value of &a is 0x%x\n", &a);
printf("Value of ptr is 0x%x\n", ptr);
printf("Value of a is %d\n", a);
printf("Value of b is %d\n", b);
printf("Value of *ptr is %d\n", *ptr);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Value of &a is 0xbfb1715c
Value of ptr is 0xbfb1715c
Value of a is 10
Value of b is 10
Value of *ptr is 10

Pointer Arithmetics in C with Examples


 Pointer Arithmetic is the set of valid arithmetic operations that can be performed on point-
ers.
 The pointer variables store the memory address of another variable.
 It doesn’t store any value.
 Hence, there are only a few operations that are allowed to perform on Pointers in C lan-
guage.
 The C pointer arithmetic operations are slightly different from the ones that we generally
use for mathematical calculations.

 These operations are:


1. Increment/Decrement of a Pointer
2. Addition of integer to a pointer
3. Subtraction of integer to a pointer
4. Subtracting two pointers of the same type
5. Comparison of pointers
1. Increment/Decrement of a Pointer
 Increment:

53
o It is a condition that also comes under addition.
o When a pointer is incremented, it actually increments by the number equal to the
size of the data type for which it is a pointer.
 For Example:
o If an integer pointer that stores address 1000 is incremented, then it will increment
by 4(size of an int), and the new address will point to 1004.
o While if a float type pointer is incremented then it will increment by 4(size of a
float) and the new address will be 1004.
 Decrement:
o It is a condition that also comes under subtraction.
o When a pointer is decremented, it actually decrements by the number equal to the
size of the data type for which it is a pointer.
 For Example:
o If an integer pointer that stores address 1000 is decremented, then it will decre-
ment by 4(size of an int), and the new address will point to 996.
o While if a float type pointer is decremented then it will decrement by 4(size of a
float) and the new address will be 996.

Note:
 It is assumed here that the architecture is 64-bit and all the data types are sized accord-
ingly.
 For example, integer is of 4 bytes.
Example of Pointer Increment and Decrement
Below is the program to illustrate pointer increment/decrement:
#include <stdio.h>
// pointer increment and decrement

54
//pointers are incremented and decremented by the size of the data type they point to
int main()
{
int a = 22;
int *p = &a;
printf("p = %u\n", p); // p = 6422288
p++;
printf("p++ = %u\n", p); //p++ = 6422292 +4 // 4 bytes
p--;
printf("p-- = %u\n", p); //p-- = 6422288 -4 // restored to original value

float b = 22.22;
float *q = &b;
printf("q = %u\n", q); //q = 6422284
q++;
printf("q++ = %u\n", q); //q++ = 6422288 +4 // 4 bytes
q--;
printf("q-- = %u\n", q); //q-- = 6422284 -4 // restored to original value

char c = 'a';
char *r = &c;
printf("r = %u\n", r); //r = 6422283
r++;
printf("r++ = %u\n", r); //r++ = 6422284 +1 // 1 byte
r--;
printf("r-- = %u\n", r); //r-- = 6422283 -1 // restored to original value
return 0;
}

Output
p = 1441900792
p++ = 1441900796
p-- = 1441900792
q = 1441900796
q++ = 1441900800
q-- = 1441900796
r = 1441900791

55
r++ = 1441900792
r-- = 1441900791
Note:
 Pointers can be outputted using %p, since, most of the computers store the address value
in hexadecimal form using %p gives the value in that form.
 But for simplicity and understanding we can also use %u to get the value in Unsigned int
form.
2. Addition of Integer to Pointer
 When a pointer is added with an integer value, the value is first multiplied by the size of
the data type and then added to the pointer.
 For Example:
o Consider the same example as above where the ptr is an integer pointer that
stores 1000 as an address.
o If we add integer 5 to it using the expression, ptr = ptr + 5, then, the final address
stored in the ptr will be ptr = 1000 + sizeof(int) * 5 = 1020.

Example of Addition of Integer to Pointer


// C program to illustrate pointer Addition
#include <stdio.h>
// Driver Code
int main()
{
// Integer variable
int N = 4;

56
// Pointer to an integer
int *ptr1, *ptr2;
// Pointer stores the address of N
ptr1 = &N;
ptr2 = &N;
printf("Pointer ptr2 before Addition: ");
printf("%p \n", ptr2);
// Addition of 3 to ptr2
ptr2 = ptr2 + 3;
printf("Pointer ptr2 after Addition: ");
printf("%p \n", ptr2);
return 0;
}
Output
Pointer ptr2 before Addition: 0x7ffca373da9c
Pointer ptr2 after Addition: 0x7ffca373daa8
3. Subtraction of Integer to Pointer
 When a pointer is subtracted with an integer value, the value is first multiplied by the size
of the data type and then subtracted from the pointer similar to addition.
 For Example:
o Consider the same example as above where the ptr is an integer pointer that
stores 1000 as an address.
o If we subtract integer 5 from it using the expression, ptr = ptr – 5, then, the final
address stored in the ptr will be ptr = 1000 – sizeof(int) * 5 = 980.

57
Example of Subtraction of Integer from Pointer
Below is the program to illustrate pointer Subtraction:
// C program to illustrate pointer Subtraction
#include <stdio.h>
// Driver Code
int main()
{
// Integer variable
int N = 4;
// Pointer to an integer
int *ptr1, *ptr2;
// Pointer stores the address of N
ptr1 = &N;
ptr2 = &N;
printf("Pointer ptr2 before Subtraction: ");
printf("%p \n", ptr2);
// Subtraction of 3 to ptr2
ptr2 = ptr2 - 3;
printf("Pointer ptr2 after Subtraction: ");
printf("%p \n", ptr2);
return 0;
}
Output
Pointer ptr2 before Subtraction: 0x7ffd718ffebc
Pointer ptr2 after Subtraction: 0x7ffd718ffeb0
4. Subtraction of Two Pointers
 The subtraction of two pointers is possible only when they have the same data type.
 The result is generated by calculating the difference between the addresses of the two
pointers and calculating how many bits of data it is according to the pointer data type.
 The subtraction of two pointers gives the increments between the two pointers.
 For Example:
o Two integer pointers say ptr1(address:1000) and ptr2(address:1004) are sub-
tracted.
o The difference between addresses is 4 bytes.
o Since the size of int is 4 bytes, therefore the increment between ptr1 and ptr2 is
given by (4/4) = 1.

58
Example of Subtraction of Two Pointer
Below is the implementation to illustrate the Subtraction of Two Pointers:
// C program to illustrate Subtraction of two pointers
#include <stdio.h>
// Driver Code
int main()
{
int x = 6; // Integer variable declaration
int N = 4;
// Pointer declaration
int *ptr1, *ptr2;
ptr1 = &N; // stores address of N
ptr2 = &x; // stores address of x
printf(" ptr1 = %u, ptr2 = %u\n", ptr1, ptr2);
// %p gives an hexa-decimal value, We convert it into an unsigned int value by
using %u Subtraction of ptr2 and ptr1
x = ptr1 - ptr2;
// Print x to get the Increment between ptr1 and ptr2
printf("Subtraction of ptr1" "& ptr2 is %d\n", x);
return 0;
}
Output
ptr1 = 2715594428, ptr2 = 2715594424
Subtraction of ptr1 & ptr2 is 1
5. Comparison of Pointers
 We can compare the two pointers by using the comparison operators in C.
 We can implement this by using all operators in C >, >=, <, <=, ==, !=.
 It returns true for the valid condition and returns false for the unsatisfied condition.
Step 1:
Initialize the integer values and point these integer values to the pointer.
Step 2:
Now, check the condition by using comparison or relational operators on
pointer variables.
Step 3:
Display the output.
Example of Pointer Comparision
// C Program to illustrare pointer comparision

59
#include <stdio.h>
int main()
{
// declaring array
int arr[5];
// declaring pointer to array name
int* ptr1 = &arr;
// declaring pointer to first element
int* ptr2 = &arr[0];
if (ptr1 == ptr2)
{
printf("Pointer to Array Name and First Element" "are Equal.");
}
else
{
printf("Pointer to Array Name and First Element" "are not Equal.");
}
return 0;
}
Output
Pointer to Array Name and First Element are Equal.

Comparison to NULL
 A pointer can be compared or assigned a NULL value irrespective of what is the pointer
type.
 Such pointers are called NULL pointers and are used in various pointer-related error-han-
dling methods.
// C Program to demonstrate the pointer comparison with NULL value
#include <stdio.h>
int main()
{
int* ptr = NULL;
if (ptr == NULL)
{
printf("The pointer is NULL");
}
else

60
{
printf("The pointer is not NULL");
}
return 0;
}
Output
The pointer is NULL
Comparison operators on Pointers using an array
 In the below approach, it results in the count of odd numbers and even numbers in an ar-
ray.
 We are going to implement this by using a pointer.
Step 1: First, declare the length of an array and array elements.
Step 2: Declare the pointer variable and point it to the first element of an
array.
Step 3: Initialize the count_even and count_odd. Iterate the for loop and
check the conditions for the number of odd elements and even
elements in an array
Step 4: Increment the pointer location ptr++ to the next element in an array
for further iteration.
Step 5: Print the result.
Example of Pointer Comparison in Array
// Pointer Comparision in Array
#include <stdio.h>
int main()
{
int n = 10; // length of an array
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int* ptr; // Declaration of pointer variable
ptr = arr; // Pointer points the first (0th index) element in an array
int count_even = 0;
int count_odd = 0;
for (int i = 0; i < n; i++)
{
if (*ptr % 2 == 0)
{
count_even++;
}

61
if (*ptr % 2 != 0)
{
count_odd++;
}
ptr++; // Pointing to the next element in an array
}
printf("No of even elements in an array is : %d", count_even);
printf("\nNo of odd elements in an array is : %d", count_odd);
}
Output
No of even elements in an array is : 5
No of odd elements in an array is : 5
Pointer Arithmetic on Arrays
 Pointers contain addresses.
 Adding two addresses makes no sense because there is no idea what it would point to.
 Subtracting two addresses lets you compute the offset between the two addresses.
 An array name acts like a pointer constant.
 The value of this pointer constant is the address of the first element.
 For Example:
o if an array is named arr then arr and &arr[0] can be used to reference the array as
a pointer.
Below is the program to illustrate the Pointer Arithmetic on arrays:
Program 1:
// C program to illustrate the array traversal using pointers
#include <stdio.h>
// Driver Code
int main()
{
int N = 5;
// An array
int arr[] = { 1, 2, 3, 4, 5 };
// Declare pointer variable
int* ptr;
// Point the pointer to first element in array arr[]
ptr = arr;
// Traverse array using ptr
for (int i = 0; i < N; i++)

62
{
// Print element at which ptr points
printf("%d ", ptr[0]);
ptr++;
}
}
Output
12345
Program 2:
// C program to illustrate the array traversal using pointers in 2D array
#include <stdio.h>
// Function to traverse 2D array using pointers
void traverseArr(int* arr, int N, int M)
{
int i, j;
// Traverse rows of 2D matrix
for (i = 0; i < N; i++)
{
// Traverse columns of 2D matrix
for (j = 0; j < M; j++)
{
// Print the element
printf("%d ", *((arr + i * M) + j));
}
printf("\n");
}
}
// Driver Code
int main()
{
int N = 3, M = 2;
// A 2D array
int arr[][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
// Function Call
traverseArr((int*)arr, N, M);
return 0;
}

63
Output
12
34
56

64
Important Questions

Part - A

1. What is mean by user defined functions?


2. With examples illustrate the difference between between an array and a pointer?
3. Give the advantages of user-defined functions
4. Describe about actual and formal parameters?
5. Clarify prototype.
6. Define pass by value.
7. Illustrate about pointer.
8. Clarify the indirection operator?
9. Name the operators (&, *).
10. Differentiate indirection and address of operators?
11. Compare pass by value and pass by reference.
12. List out the function prototype.
13. List some points about pointer to pointer?
14.Null pointer-Define.
15. Debug the following C program.
main();
{
int a,*p;
p=&a;
print("\n Enter the value : ");
scanf(%d",&a);
printf("\n Value of a is : %d",a);
printf("\n Address of a is : %u",&a);
printf(“\n The value of *p is : %d”,*p);
printf("\n Value of p is : %d",p);
printf("\n Address of p is : %u",&p);
};
16. Give any two features of pointers.
17. Differentiate between library functions and programmer defined functions.
18.Write the output of the following C program
main()
{

65
int v=3;
int *pv;
pv=&v;
printf(“\n *pv=%d v=%d”, *pv,v);
*pv=5;
printf(“\n *pv=%d v=%d”, *pv,v);
}

Part - B

1. Explain function prototype with example.


2. Classify the functions based on input and output
3. Classify the functions based on return type and arguments.
4. Explain the Parameter passing methods.
5. Write a C program to find the n Fibonacci numbers using recursive function.
6. Write a C program to find the biggest of three numbers using function
7. Explain Recursive Function with example. Explain the classification of recursive func-
tion.
8. How do you pass array as argument to function. Explain with example.
9. Define pointer. Write how to declare pointer and how to initialize it.
10. Explain Pointer arithmetic with example.
11. Explain string() functions with example
12. Explain math() functions with example.
13. Write a C program to sort a given array of numbers using function.
14. What is an array of pointer? How it can be declared? Explain with an example?
15. Write a C program to find factorial of n numbers.
16. Explain pointer operators.
17. Write a C program to sort a given array of names or strings using function.
18. Write a C program to find the sum of all elements of an array using function.
19. Write a C program to find determinant of a 3*3 matrix using function.
20. Write a C program to find transpose of a matrix using function.
21. Develop a C function that checks whether two matrices can be multiplied or not, If
yes, multiply them. Illustrate the use of developed function
22. Write a C program to illustrate passing pointer as a parameter/argument to a function
23. Discuss about pass by value and pass by reference

66

You might also like