You are on page 1of 24

CS8251 Programming in C

UNIT – III
FUNCTIONS AND POINTERS Introduction to functions: Function prototype, function definition, function
call, Built-in functions (string functions, math functions) – Recursion – Example Program: Computation of
Sine series, Scientific calculator using built-in functions, Binary Search using recursive functions – Pointers
– Pointer operators – Pointer arithmetic – Arrays and pointers – Array of pointers – Example Program:
Sorting of names – Parameter passing: Pass by value, Pass by reference – Example Program: Swapping of
two numbers and changing the value of a variable using pass by reference

3.1 Introduction to functions


A function is a block of code that performs a specific task.
Suppose, a program related to graphics needs to create a circle and color it depending upon the radius and
color from the user. You can create two functions to solve this problem:
 create a circle function
 color function
Dividing complex problem into small components makes program easy to understand and use.
Types of functions in C programming
Depending on whether a function is defined by the user or already included in C compilers, there are two
types of functions in C programming There are two types of functions in C programming:
 Standard library functions
 User defined functions
Standard library functions
The standard library functions are built-in functions in C programming to handle tasks such as
mathematical computations, I/O processing, string handling etc.
These functions are defined in the header file. When you include the header file, these functions are
available for use. For example:
The printf() is a standard library function to send formatted output to the screen (display output on
the screen). This function is defined in "stdio.h"header file. There are other numerous library
functions defined under "stdio.h", such
as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all these functions are
available for use.
User-defined functions
As mentioned earlier, C allow programmers to define functions. Such functions created by the user are
called user-defined functions.
Depending upon the complexity and requirement of the program, you can create as many user-defined
functions as you want.
How user-defined function works?

#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}
int main()
{
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
}

54
CS8251 Programming in C

The execution of a C program begins from the main() function.


When the compiler encounters functionName(); inside the main function, control of the program jumps to

void functionName()

And, the compiler starts executing the codes inside the user-defined function.
The control of the program jumps to statement next to functionName(); once all the codes inside the function
definition are executed.
A function is a block of code that performs a specific task.
C allows you to define functions according to your need. These functions are known as user-defined
functions. For example:
Suppose, you need to create a circle and color it depending upon the radius and color.
You can create two functions to solve this problem:
 createCircle() function
 color() function
Example: User-defined function
Here is a example to add two integers. To perform this task, a user-defined function addNumbers() is
defined.
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0;
}
int addNumbers(int a,int b) // function definition
{
int result;
result=a+b;
return result; //return statement
}

3.1.1 Function prototype


A function prototype is simply the declaration of a function that specifies function's name, parameters
and return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function may later be used in the
program.
Syntax of function prototype

returnType functionName(type1 argument1, type2 argument2,...);

In the above example, int addNumbers(int a, int b); is the function prototype which provides
following information to the compiler:
1. name of the function is addNumbers()
2. return type of the function is int
3. two arguments of type int are passed to the function
The function prototype is not needed if the user-defined function is defined before the main ()
function.
55
CS8251 Programming in C

3.1.2 Function definition


Function definition contains the block of code to perform a specific task i.e. in this case, adding two
numbers and returning it.
Syntax of function definition

returnType functionName(type1 argument1, type2 argument2, ...)


{
//body of the function
}

When a function is called, the control of the program is transferred to the function definition. And, the
compiler starts executing the codes inside the body of a function.
3.1.3 Function Call
Control of the program is transferred to the user-defined function by calling it.
Syntax of function call

functionName(argument1, argument2, ...);

In the above example, function call is made using addNumbers(n1,n2); statement inside the main().

Passing arguments to a function


In programming, argument refers to the variable passed to the function. In the above example, two
variables n1 and n2 are passed during function call.
The parameters a and b accepts the passed arguments in the function definition. These arguments are called
formal parameters of the function.

The type of arguments passed to a function and the formal parameters must match, otherwise the compiler
throws error.
If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also should be of float
type.
A function can also be called without passing an argument.

56
CS8251 Programming in C

Return Statement
The return statement terminates the execution of a function and returns a value to the calling function. The
program control is transferred to the calling function after return statement.
In the above example, the value of variable result is returned to the variable sum in the main() function.
Syntax of return statement

return (expression);

For example,

return a;
return (a+b);

The type of value returned from the function and the return type specified in
function prototype and function definition must match

Remember, function name is an identifier and should be unique.


This is just an overview on user-defined function.
 User-defined Function in C programming
 Types of user-defined Functions
Advantages of user-defined function
1. The program will be easier to understand, maintain and debug.
2. Reusable codes that can be used in other programs
3. A large program can be divided into smaller modules. Hence, a large project can
be divided among many programmers.
For better understanding of arguments and return value from the function, user-defined functions can
be categorized as:
 Function with no arguments and no return value
 Function with no arguments and a return value
 Function with arguments and no return value
 Function with arguments and a return value.
The 4 programs below check whether an integer entered by the user is a prime number or not. And, all these
programs generate the same output.

Example #1: No arguments passed and no return Value


#include <stdio.h>
void checkPrimeNumber();
int main()
{
checkPrimeNumber(); // no argument is passed to prime()
57
CS8251 Programming in C

return 0;
}
// return type of the function is void becuase no value is returned from the function void
checkPrimeNumber()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2; i <= n/2; ++i)
{
if(n%i == 0)
{
flag = 1;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}

The checkPrimeNumber() function takes input from the user, checks whether it is a prime number or
not and displays it on the screen.
The empty parentheses in checkPrimeNumber(); statement inside the main()function indicates that no
argument is passed to the function.
The return type of the function is void. Hence, no value is returned from the function.

Example #2: No arguments passed but a return value


#include <stdio.h>
int getInteger();
int main()
{
int n, i, flag = 0;
// no argument is passed to the function
// the value returned from the function is assigned to n n = getInteger();
for(i=2; i<=n/2; ++i)
{
if(n%i==0){
flag = 1;
break;
}
}
if (flag == 1)

printf("%d is not a prime number.", n);


else
printf("%d is a prime number.", n);
return 0;
}
// getInteger() function returns integer entered by the user int getInteger()
{
int n;
58
CS8251 Programming in C

printf("Enter a positive integer: ");


scanf("%d",&n);
return n;
}

The empty parentheses in n = getInteger(); statement indicates that no argument is passed to the
function. And, the value returned from the function is assigned to n. Here, the getInteger() function
takes input from the user and returns it. The code to check whether a number is prime or not is inside
the main() function.

Example #3: Argument passed but no return value


#include <stdio.h>
void checkPrimeAndDisplay(int n);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
// n is passed to the function
checkPrimeAndDisplay(n);
return 0;
}
// void indicates that no value is returned from the function void
checkPrimeAndDisplay(int n)
{
int i, flag = 0;

for(i=2; i <= n/2; ++i)


{
if(n%i == 0){
flag = 1

break;
}
}
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}

The integer value entered by the user is passed to checkPrimeAndDisplay()function. Here, the
checkPrimeAndDisplay() function checks whether the argument passed is a prime number or not and
displays the appropriate message.

Example #4: Argument passed and a return value


#include <stdio.h>
int checkPrimeNumber(int n);
int main()
{
59
CS8251 Programming in C

int n, flag;
printf("Enter a positive integer: ");
scanf("%d",&n);
// n is passed to the checkPrimeNumber() function
// the value returned from the function is assigned to flag variable flag =
checkPrimeNumber(n);
if(flag==1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
// integer is returned from the function int
checkPrimeNumber(int n)
{
/* Integer value is returned from function checkPrimeNumber() */ int i;
for(i=2; i <= n/2; ++i)
{
if(n%i == 0)
return 1;
}
return 0;
}

The input from the user is passed to checkPrimeNumber() function.


The checkPrimeNumber() function checks whether the passed argument is prime or not. If the passed
argument is a prime number, the function returns 0. If the passed argument is a non-prime number, the
function returns 1. The return value is assigned to flag variable.
Then, the appropriate message is displayed from the main() function.
Which approach is better?
Well, it depends on the problem you are trying to solve. In case of this problem, the last approach is better.
A function should perform a specific task. The checkPrimeNumber() function doesn't take input from the
user nor it displays the appropriate message. It only checks whether a number is prime or not, which makes
code modular, easy to understand and debug.

3.1.4 Built-in functions


Some of the "commands" in C are not really "commands" at all but are functions. For example, we have
been using printf and scanf to do input and output, and we have used rand to generate random numbers
- all three are functions.
There are a great many standard functions that are included with C compilers and while these are not really
part of the language, in the sense that you can re-write them if you really want to, most C programmers think
of them as fixtures and fittings. Later in the course we will look into the mysteries of how C gains access to
these standard functions and how we can extend the range of the standard library. But for now a list of the
most common libraries and a brief description of the most useful functions they contain follows:
1. stdio.h: I/O functions:
a. getchar() returns the next character typed on the keyboard.
b. putchar() outputs a single character to the screen.
c. printf() as previously described
d. scanf() as previously described
2. string.h: String functions
a. strcat() concatenates a copy of str2 to str1
b. strcmp() compares two strings
60
CS8251 Programming in C

c. strcpy() copys contents of str2 to str1


3. ctype.h: Character functions
a. isdigit() returns non-0 if arg is digit 0 to 9
b. isalpha() returns non-0 if arg is a letter of the alphabet
c. isalnum() returns non-0 if arg is a letter or digit
d. islower() returns non-0 if arg is lowercase letter
e. isupper() returns non-0 if arg is uppercase letter
4. math.h: Mathematics functions
a. acos() returns arc cosine of arg
b. asin() returns arc sine of arg
c. atan() returns arc tangent of arg
d. cos() returns cosine of arg
e. exp() returns natural logarithim e
f. fabs() returns absolute value of num
g. sqrt() returns square root of num
5. time.h: Time and Date functions
a. time() returns current calender time of system
b. difftime() returns difference in secs between two times
c. clock() returns number of system clock cycles since program execution
6. stdlib.h:Miscellaneous functions
a. malloc() provides dynamic memory allocation, covered in future sections
b. rand() as already described previously
c. srand() used to set the starting point for rand()
List Of Inbuilt C Functions In Math.h File:
“math.h” header file supports all the mathematical related functions in C language. All the arithmetic
functions used in C language are given below.

Function Description
floor ( ) This function returns the nearest integer which is less than or equal
to the argument passed to this function.
round ( ) This function returns the nearest integer value of the
float/double/long double argument passed to this function. If decimal
value is from “.6 to .9”, it returns the integer value greater than the
argument.
ceil ( ) This function returns nearest integer value which is greater than or
equal to the argument passed to this function.
sin ( ) This function is used to calculate sine value.
cos ( ) This function is used to calculate cosine.
cosh() This function is used to calculate hyperbolic cosine.
exp() This function is used to calculate the exponential “e” to the xth
power.
tan() This function is used to calculate tangent.
tanh() This function is used to calculate hyperbolic tangent.
sinh() This function is used to calculate hyperbolic sine.
log() This function is used to calculate natural logarithm.
Log10() This function is used to calculate base 10 logarithm
sqrt ( ) This function is used to find square root of the argument passed
to this function.
pow() This is used to find the power of the given number.
trunc.(.) This function truncates the decimal value from floating point value
and returns integer value.

61
CS8251 Programming in C

List Of Inbuilt C Functions In string.h File


All C inbuilt functions which are declared in string.h header file are given below. The source code
for string.h header file is also given below for your reference.

String Functions Description


strcat() Concatenates str2 at the end of str1
strncat() Append a portion of string to another.
strcpy() Copies str2 into str1
strncpy() Copies given number of characters of one string to another
strlen() Gives the length of str1
strcmp ( ) Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0 if
str1 > str2
strcmpi ( ) Same as strcmp() function. But, this function negotiates case. “A”
and “a” are treated as same.
strchr ( ) Returns pointer to first occurrence of char in str1
strrchr ( ) last occurrence of given character in a string is found
strstr ( ) Returns pointer to first occurrence of str2 in str1
strrstr ( ) Returns pointer to last occurrence of str2 in str1
strdup ( ) Duplicates the string
strlwr ( ) Converts string to lowercase
strupr ( ) Converts string to uppercase
strrev ( ) Reverses the given string
strset ( ) Sets all character in a string to given character
strnset ( ) It sets the portion of characters in a string to given character
strtok ( ) Tokenizing given string using delimiter
memset() It is used to initialize a specified number of bytes to null or any other
value in the buffer
memcpy() It is used to copy a specified number of bytes from one memory to
another
memmove() It is used to copy a specified number of bytes from one memory to
another or to overlap on same memory
memcmp() It is used to compare specified number of characters from two
buffers.
memicmp() It is used to compare specified number of characters from two
buffers regardless of the case of the charcters

3.2 Recursion
Recursion is the process of repeating items in a self-similar way. In programming languages, if a program
allows you to call a function inside the same function, then it is called a recursive call of the function.
void recursion() {
recursion(); /* function calls itself */
}

int main() {
recursion();
}

62
CS8251 Programming in C

The C programming language supports recursion, i.e., a function to call itself. But while using recursion,
programmers need to be careful to define an exit condition from the function, otherwise it will go into an
infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial
of a number, generating Fibonacci series, etc. Number Factorial

The following example calculates the factorial of a given number using a recursive function −
#include <stdio.h>

int factorial(unsigned int i) {


if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}

int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i)); return 0;
}
When the above code is compiled and executed, it produces the following result −
Factorial of 12 is 479001600
Fibonacci Series
The following example generates the Fibonacci series for a given number using a recursive function −
#include <stdio.h>
int fibonacci(int i) {
if(i == 0) {
return 0;
}
if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main() {
int i;
for (i = 0; i < 10; i++) {
printf("%d\t\n", fibonacci(i));
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
0
1
1
2
3
5
8
13
63
CS8251 Programming in C

21
34

3.3 Example Program:


3.3.1 Computation of Sine series Sine Series:
Sine Series is a series which is used to find the value of Sin(x).
where, x is the angle in degree which is converted to Radian.
The formula used to express the Sin(x) as Sine Series is

Expanding the above notation, the formula of Sine Series is

For example,
Let the value of x be 30.

So, Radian value for 30 degree is 0.52359.

So, the value of Sin(30) is 0.5.


Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
float x, sum,t;
clrscr();
printf (“Enter the value for x:”);
scanf(%f”,&x);
printf(“Enter the value for n;”);
scanf(%d”,&n);
x=x*3.14159 / 180;
t=x;
sum=x;
for ( i=1;i<=n;i++)
{
T=(t*(-1)*x*x)/(2*i*(2*i+1));
sum=sum+t;
}
printf( “The value of Sin(%f)=%.4f%”,x,sum);
getch();
}

64
CS8251 Programming in C

Working:
 First the computer reads the value of „x‟ and „n‟ from the user.
 Then „x‟ is converted to radian value.
 Then using for loop the value of Sin(x) is calculate.
 Finally the value of Sin(x) is printed.
Step by Step working of the above Program Code:
Let us assume that the user enters the value of „x‟ as 45 and „n‟ as 4.
1. Converting „x‟ to radian value
x = x * 3.14159 / 180(x = 45 * 3.14159 / 180) So, x=0.785398
2. It assigns t=x and sum=x (i.e. t=0.785398 and sum=0.785398)
3. It assigns the value of i=1 and the loop continues till the condition of the for loop is true.
3.1.i<=n (1<=4) for loop condition is true
t = (0.785398 * (-1) * 0.785398 * 0.785398)/(2 * 1 * (2 * 1 + 1))
So, t = – 0.08074
sum = 0.785398 + (- 0.08074)
So, sum=0.70465
i++
So, i=2
3.2. i<=n (2<=4) for loop condition is true
t = (- 0.08074 * (-1) * 0.785398 * 0.785398)/(2 * 2 * (2 * 2 + 1))
So, t = 0.00249
sum = 0.70465 + 0.00249
So, sum=0.70714
i++
So, i=3
3.3. i<=n (3<=4) for loop condition is true
t = (0.00249 * (-1) * 0.785398 * 0.785398)/(2 * 3 * (2 * 3 + 1))
So, t = – 0.000032
sum = 0.70714 + (- 0.000032)
So, sum=0.707108
i++
So, i=4
3.4. i<=n (4<=4) for loop condition is true
t = (- 0.000032 * (-1) * 0.785398 * 0.785398)/(2 * 4 * (2 * 4 + 1))
So, t = 0.000000274
sum = 0.707108 + 0.000000274
So, sum=0.707108274
i++
So, i=5
3.5. i<=n (5<=4) for loop condition is false
It comes out of the for loop.
4. Finally it prints The value of Sin(0.785398) = 0.7071
5. Thus program execution is completed.
Output:
Enter the value for x: 45
Enter the value for m: 5
The value of sin(0.7853920)=0.7071
3.3.3 Binary Search using Recursion
/** C Program to Perform Binary Search using Recursion*/
#include <stdio.h>
void binary_search(int [], int, int, int);
65
CS8251 Programming in C

void bubble_sort(int [], int);


int main()
{
int key, size, i;
int list[25];
printf("Enter size of a list: ");
scanf("%d", &size);
printf("Generating random numbers\n");
for(i = 0; i < size; i++)
{
list[i] = rand() % 100;
printf("%d ", list[i]);
}
bubble_sort(list, size);
printf("\n\n");
printf("Enter key to search\n");
scanf("%d", &key);
binary_search(list, 0, size, key);
}
void bubble_sort(int list[], int size)
{
int temp, i, j;
for (i = 0; i < size; i++)
{
for (j = i; j < size; j++)
{
if (list[i] > list[j])
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}}
}}
void binary_search(int list[], int lo, int hi, int key)
{
int mid;
if (lo > hi)
{
printf("Key not found\n");
return;
}
mid = (lo + hi) / 2;
if (list[mid] == key)
{
printf("Key found\n");
}
else if (list[mid] > key)
{
binary_search(list, lo, mid - 1, key);
}
else if (list[mid] < key)
{
66
CS8251 Programming in C

binary_search(list, mid + 1, hi, key);


}
}}
Output:
Enter size of a list: 10
Generating random numbers
83 86 77 15 93 35 86 92 49 21
Enter key to search
21
Key found

3.4 Pointers
Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with pointers,
and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it
becomes necessary to learn pointers to become a perfect C programmer. Let's start learning them in simple
and easy steps.
As you know, every variable is a memory location and every memory location has its address defined which
can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the
following example, which prints the address of the variables defined −
#include <stdio.h>
int main ()
{
int var1;
char var2[10];
printf("Address of var1 variable: %x\n", &var1 );
printf("Address of var2 variable: %x\n", &var2 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6
What are Pointers?
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory
location. Like any variable or constant, you must declare a pointer before using it to store any variable
address. The general form of a pointer variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the
pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication.
However, in this statement the asterisk is being used to designate a variable as a pointer. Take a look at
some of the valid pointer declarations −
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the
same, a long hexadecimal number that represents a memory address. The only difference between
pointers of different data types is the data type of the variable or constant that the pointer points to.

67
CS8251 Programming in C

How to Use Pointers?


There are a few important operations, which we will do with the help of pointers very frequently. (a) We
define a pointer variable, (b) assign the address of a variable to a pointer and (c) finally access the value at
the address available in the pointer variable. This is done by using unary operator * that returns the value
of the variable located at the address specified by its operand. The following example makes use of these
operations −
#include <stdio.h>
int main ()
{
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var );
/* address stored in pointer variable */
printf("Address stored in ip variable: %x\n", ip );
/* access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20
NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact
address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL
is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the
following program −
#include <stdio.h>
int main ()
{
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
When the above code is compiled and executed, it produces the following result −
The value of ptr is 0
In most of the operating systems, programs are not permitted to access memory at address 0 because that
memory is reserved by the operating system. However, the memory address 0 has special significance; it
signals that the pointer is not intended to point to an accessible memory location. But by convention, if a
pointer contains the null (zero) value, it is assumed to point to nothing.
To check for a null pointer, you can use an 'if' statement as follows –
if (ptr) /* succeeds if p is not null */
if (!ptr) /* succeeds if p is null */
3.5 Pointer Operator
Operator Operator Name Purpose
* Value at Operator Gives Value stored at Particular address
& Address Operator Gives Address of Variable

68
CS8251 Programming in C

In order to create pointer to a variable we use “*” operator and to find the address of Variable we use “&”
operator.
Don‟t Consider “&” and “*” operator as Logical AND and Multiplication Operator in Case of Pointer.
Important Notes :
1. „&‟ operator is called as address Operator
2. ‘*’ is called as ‘Value at address’ Operator
3. „Value at address’ Operator gives „Value stored at Particular address.
4. ‘Value at address’ is also called as ‘Indirection Operator’
Pointer Operators :
#include<stdio.h>
int main()
{
int n = 20;
printf("\nThe address of n is %u",&n);
printf("\nThe Value of n is %d",n);
printf("\nThe Value of n is %d",*(&n));
}
Output:
The address of n is 1002
The Value of n is 20
The Value of n is 20
How *(&n) is same as printing the value of n ?
&n Gives address of the memory location whose name is „n‟

* means value at Operator gives value at address specified by &n.

m = Address of n is stored in m , but remember that m is not ordinary variable like


&n „n‟

So Ccompiler must provide space for it in memory.Below is Step by Step Calculation to compute the value –
m = * ( &n )
= * ( Address of Variable 'n')
= * ( 1000 )
= Value at Address 1000
= 20
What Does following declaration tells compiler?
int *ptr;
1. „ptr‟ is declared as that „ptr‟ will be used only for storing the address of the integer valued variables
2. We can also say that „ptr‟ points to integer
3. Value at the address contained in „ptr‟ is integer .
S. Memory
no. Declaration Explanation Required
p is going to store address of
1 int *p integer value 2 bytes
q is going to store address of
2 float *q floating value 2 bytes
ch is going to store address of
3 char *ch character variable 2 bytes
69
CS8251 Programming in C

3.6 Pointer arithmetic


A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic operations on
a pointer just as you can on a numeric value. There are four arithmetic operators that can be used on
pointers: ++, --, +, and -
To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address
1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer −
ptr++
After the above operation, the ptr will point to the location 1004 because each time ptr is incremented, it
will point to the next integer location which is 4 bytes next to the current location. This operation will
move the pointer to the next memory location without impacting the actual value at the memory location.
If ptrpoints to a character whose address is 1000, then the above operation will point to the location 1001
because the next character will be available at 1001.
Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the variable pointer can be
incremented, unlike the array name which cannot be incremented because it is a constant pointer. The
following program increments the variable pointer to access each succeeding element of the array −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = var;
for ( i = 0; i < MAX; i++) {
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
/* move to the next location */
ptr++;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Value of var[2] = 200

Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes
of its data type as shown below −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--) {
70
CS8251 Programming in C

printf("Address of var[%d] = %x\n", i-1, ptr ); printf("Value


of var[%d] = %d\n", i-1, *ptr );
/* move to the previous location */
ptr--;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var[2] = bfedbcd8
Value of var[2] = 200
Address of var[1] = bfedbcd4
Value of var[1] = 100
Address of var[0] = bfedbcd0
Value of var[0] = 10

Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to
variables that are related to each other, such as elements of the same array, then p1 and p2 can be
meaningfully compared.
The following program modifies the previous example − one by incrementing the variable pointer so
long as the address to which it points is either less than or equal to the address of the last element of the
array, which is &var[MAX - 1] −

#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have address of the first element in pointer */
ptr = var;
i = 0;
while ( ptr <= &var[MAX - 1] ) {
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
/* point to the previous location */
ptr++;
i++;
}
return 0;
}
When the above code is compiled and executed, it produces the following result –
Address of var[0] = bfdbcb20
Value of var[0] = 10
Address of var[1] = bfdbcb24
Value of var[1] = 100
Address of var[2] = bfdbcb28
Value of var[2] = 200

71
CS8251 Programming in C

3.7 Arrays and Pointers


Arrays are closely related to pointers in C programming but the important difference between them is that,
a pointer variable takes different addresses as value whereas, in case of array it is fixed.
This can be demonstrated by an example:
#include <stdio.h>
int main()
{
char charArr[4];
int i;
for(i = 0; i < 4; ++i)
{
printf("Address of charArr[%d] = %u\n", i, &charArr[i]);
}
return 0;
}
When you run the program, the output will be:

Address of charArr[0] = 28ff44


Address of charArr[1] = 28ff45
Address of charArr[2] = 28ff46
Address of charArr[3] = 28ff47

Note: You may get different address of an array.


Notice, that there is an equal difference (difference of 1 byte) between any two consecutive
elements of array charArr.
But, since pointers just point at the location of another variable, it can store any address.
Relation between Arrays and Pointers
Consider an array:

int arr[4];

In C programming, name of the array always points to address of the first element of an array.
In the above example, arr and &arr[0] points to the address of the first element. &arr[0] is
equivalent to arr Since, the addresses of both are the same, the values of arr and &arr[0] are also
the same.
arr[0] is equivalent to *arr (value of an address of the pointer)
Similarly,
&arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).
&arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
&arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3).&arr[i] is equivalent to (arr
+ i) AND, arr[i] is equivalent to *(arr + i).
In C, you can declare an array and can use pointer to alter the data of an array.
Example: Program to find the sum of six numbers with arrays and pointers
#include <stdio.h>
int main()
{
int i, classes[6],sum = 0;
72
CS8251 Programming in C

printf("Enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
{
// (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));

// *(classes + i) is equivalent to classes[i] sum +=


*(classes + i);
}
printf("Sum = %d", sum);
return 0;
}
Output

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

3.8 Array of pointers


Before we understand the concept of arrays of pointers, let us consider the following example, which uses
an array of 3 integers −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i;
for (i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, var[i] );
}
return 0;
}

When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
There may be a situation when we want to maintain an array, which can store pointers to an int or char or
any other data type available. Following is the declaration of an array of pointers to an integer −
int *ptr[MAX];
It declares ptr as an array of MAX integer pointers. Thus, each element in ptr, holds a pointer to an int
value. The following example uses three integers, which are stored in an array of pointers, as follows −
#include <stdio.h>

const int MAX = 3;

73
CS8251 Programming in C

int main () {

int var[] = {10, 100, 200};


int i, *ptr[MAX];

for ( i = 0; i < MAX; i++) {


ptr[i] = &var[i]; /* assign the address of integer. */

for ( i = 0; i < MAX; i++) {


printf("Value of var[%d] = %d\n", i, *ptr[i] );
}

return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
You can also use an array of pointers to character to store a list of strings as follows − #include <stdio.h>
const int MAX = 4;
int main () {
char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali"
};

int i = 0;
for ( i = 0; i < MAX; i++) {
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali

3.9 Example Program


Sorting of names
/* This program would sort the input strings in
* an ascending order and would display the same */
#include<stdio.h>
#include<string.h>

74
CS8251 Programming in C

int main(){
int i,j,count;
char str[25][25],temp[25];
puts("How many strings u are going to enter?: ");
scanf("%d",&count);
puts("Enter Strings one by one: ");
for(i=0;i<=count;i++)
gets(str[i]);
for(i=0;i<=count;i++)
for(j=i+1;j<=count;j++){
if(strcmp(str[i],str[j])>0){
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("Order of Sorted Strings:");
for(i=0;i<=count;i++)
puts(str[i]);

return 0;
}
Output:
How many strings u are going to enter?: 3
Enter Strings one by one:
john
Arul
Peter
Order of Sorted Strings:
Arul
Peter
John
3.10 Parameter passing
There are different ways in which parameter data can be passed into and out of methods and functions. Let us
assume that a function B() is called from another function A(). In this case A is called the “caller function”
and B is called the “called
function or callee function”. Also, the arguments which A sends to B are called actual arguments and the
parameters of B are called formal arguments.
Terminology
 Formal Parameter : A variable and its type as they appear in the prototype of the function or method.
 Actual Parameter : The variable or expression corresponding to a formal parameter that appears in the
function or method call in the calling environment.
 Modes:
 IN: Passes info from caller to calle.
 OUT: Callee writes values in caller.
 IN/OUT: Caller tells callee value of variable, which may be updated by callee.
Important methods of Parameter Passing
3.10.1 Pass By Value : This method uses in-mode semantics. Changes made to formal parameter do not get
transmitted back to the caller. Any modifications to the formal parameter variable inside the called
function or method affect only the separate storage location and will not be reflected in the actual
parameter in the calling environment. This method is also called as call by value.
// C program to illustrate
75
CS8251 Programming in C

// call by value
#include <stdio.h>
void func(int a, int b)
{
a += b;
printf("In func, a = %d b = %d\n", a, b);
}
int main(void)
{
int x = 5, y = 7;

// Passing parameters func(x, y);


printf("In main, x = %d y = %d\n", x, y); return 0;
}

Output:
In func, a = 12 b = 7
In main, x = 5 y = 7

Shortcomings:
 Inefficiency in storage allocation
 For objects and arrays, the copy semantics are costly
3.10.2 Pass by reference(aliasing) :
This technique uses in/out-modesemantics. Changes made to formal parameter do get transmitted back to the
caller through parameter passing. Any changes to the formal parameter are reflected in the
actual parameter in the calling environment as formal parameter receives a reference (or pointer) to the actual
data. This method is also called as <em>call by reference. This method is efficient in both time and space.
// C program to illustrate
// call by reference

// #include <stdio.h>
void swapnum(int* i, int* j)
{
int temp = *i;
*i = *j;
*j = temp;
}
int main(void)
{
int a = 10, b = 20;
// passing parameters
swapnum(&a, &b);
printf("a is %d and b is %d\n", a, b);
return 0;
}
Output:
a is 20 and b is 10

76
CS8251 Programming in C

3.11 Example Program


3.11.1 Swapping of two numbers
#include <stdio.h>
int main()
{
int x, y, temp;
printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);
printf("Before Swapping\nx = %d\ny = %d\n",x,y);
temp = x;
x = y;
y = temp;
printf("After Swapping\nx = %d\ny = %d\n",x,y);
return 0;
}

Output of program:
Enter the value of x and y: 3 5
Before Swapping
x=3
y=5
After Swapping
x=5
y=3
3.11.2 Changing the value of a variable using pass by reference
#include <stdio.h>
void swap(int*, int*); //Swap function declaration
int main()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
//Swap function definition
void swap(int *a, int *b)
{
int t;
t = *b; *b =*a; *a
= t;
}
Output of program:
Enter the value of x and y: 3 5
Before Swapping
x=3
y=5
After Swapping
x=5
y=3

77

You might also like