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

UNIT III

The document provides an overview of functions and pointers in C programming, detailing the types of functions (standard library and user-defined), function prototypes, definitions, and calls. It explains how to pass parameters, return values, and the advantages of using user-defined functions for modular programming. Additionally, it lists various built-in functions available in C libraries for tasks such as mathematical computations and string handling.

Uploaded by

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

UNIT III

The document provides an overview of functions and pointers in C programming, detailing the types of functions (standard library and user-defined), function prototypes, definitions, and calls. It explains how to pass parameters, return values, and the advantages of using user-defined functions for modular programming. Additionally, it lists various built-in functions available in C libraries for tasks such as mathematical computations and string handling.

Uploaded by

thirunavukkarasu
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/ 33

CS8251 Dept of CSE 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()
{
... .. ...

TPGIT/CSE 1
CS8251 Dept of CSE Programming in C

... .. ...
}

int main()
{
... .. ...
... .. ...

functionName();

... .. ...
... .. ...
}

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);

TPGIT/CSE 2
CS8251 Dept of CSE Programming in C

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.
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, ...);

TPGIT/CSE 3
CS8251 Dept of CSE Programming in C

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.
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);

TPGIT/CSE 4
CS8251 Dept of CSE Programming in C

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()
return 0;
}

TPGIT/CSE 5
CS8251 Dept of CSE Programming in C

// 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){fla
g = 1;
break;
}
}

if (flag == 1)

TPGIT/CSE 6
CS8251 Dept of CSE Programming in C

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;

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;

TPGIT/CSE 7
CS8251 Dept of CSE Programming in C

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()
{
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;

TPGIT/CSE 8
CS8251 Dept of CSE Programming in C

}
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
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

TPGIT/CSE 9
CS8251 Dept of CSE Programming in C

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

This function returns the nearest


integer which is less than or equal to
floor ( ) the argument passed to this function.

This function returns the nearest


integer value of the float/double/long
double argument passed to this
function. If decimal value is from “.1 to
.5”, it returns integer value less than the
argument. If decimal value is from “.6
to .9”, it returns the integer value
round ( ) greater than the argument.

This function returns nearest integer


value which is greater than or equal
ceil ( ) to the argument passed to this function.

This function is used to calculate sine


sin ( ) value.

This function is used to calculate


cos ( ) cosine.

This function is used to calculate


cosh ( ) hyperbolic cosine.

This function is used to calculate the


exp ( ) exponential “e” to the xth power.

This function is used to calculate


tan ( ) tangent.

This function is used to calculate


tanh ( ) hyperbolic tangent.

sinh ( ) This function is used to calculate

TPGIT/CSE 10
CS8251 Dept of CSE Programming in C

hyperbolic sine.

This function is used to calculates


log ( ) natural logarithm.

This function is used to calculates base


log10 ( ) 10 logarithm.

This function is used to find square


root of the argument passed to this
sqrt ( ) function.

This is used to find the power of the


pow ( ) given number.

This function truncates the decimal


value from floating point value and
trunc.(.) returns integer value.

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

Appends a portion of string to


strncat ( ) another

strcpy ( ) Copies str2 into str1

Copies given number of characters


strncpy ( ) of one string to another

strlen ( ) Gives the length of str1

Returns 0 if str1 is same as


str2. Returns <0 if strl < str2. Returns
strcmp ( ) >0 if str1 > str2

Same as strcmp() function. But, this


function negotiates case. “A” and
strcmpi ( ) “a” are treated as same.

Returns pointer to first occurrence of


strchr ( ) char in str1

TPGIT/CSE 11
CS8251 Dept of CSE Programming in C

last occurrence of given character in


strrchr ( ) a string is found

Returns pointer to first occurrence of


strstr ( ) str2 in str1

Returns pointer to last occurrence of


strrstr ( ) str2 in str1

strdup ( ) Duplicates the string

strlwr ( ) Converts string to lowercase

strupr ( ) Converts string to uppercase

strrev ( ) Reverses the given string

Sets all character in a string to given


strset ( ) character

It sets the portion of characters in a


strnset ( ) string to given character

Tokenizing given string using


strtok ( ) delimiter

It is used to initialize a specified


number of bytes to null or any other
memset() value in the buffer

It is used to copy a specified number


of bytes from one memory to
memcpy() another

It is used to copy a specified number


of bytes from one memory to
another or to overlap on same
memmove() memory.

It is used to compare specified


number of characters from two
memcmp() buffers

It is used to compare specified


number of characters from two
buffers regardless of the case of the
memicmp() characters

It is used to locate the first


memchr() occurrence of the character in the

TPGIT/CSE 12
CS8251 Dept of CSE Programming in C

specified string

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()
;
}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.
NumberFactorial
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
FibonacciSeries
The following example generates the Fibonacci series for a given number using a
recursive function −
#include <stdio.h>

int fibonacci(int i) {

TPGIT/CSE 13
CS8251 Dept of CSE Programming in C

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

TPGIT/CSE 14
CS8251 Dept of CSE Programming in C

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;

/* Loop to calculate the value of Sine */


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();
}
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

TPGIT/CSE 15
CS8251 Dept of CSE Programming in C

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:

3.3.3 Binary Search using Recursion


1. /*
2. * C Program to Perform Binary Search using Recursion
3. */

TPGIT/CSE 16
CS8251 Dept of CSE Programming in C

4. #include <stdio.h>5.
6. void binary_search(int [], int, int, int);
7. void bubble_sort(int [], int);
8.
9. int main()
10. {
11. int key, size, i;
12. int list[25];
13.
14. printf("Enter size of a list: ");
15. scanf("%d", &size);
16. printf("Generating random numbers\n");
17. for(i = 0; i < size; i++)
18. {
19. list[i] = rand() % 100;
20. printf("%d ", list[i]);
21. }
22. bubble_sort(list, size);
23. printf("\n\n");
24. printf("Enter key to search\n");
25. scanf("%d", &key);
26. binary_search(list, 0, size, key);
27.
28. }
29.
30. void bubble_sort(int list[], int size)
31. {
32. int temp, i, j;
33. for (i = 0; i < size; i++)
34. {
35. for (j = i; j < size; j++)
36. {
37. if (list[i] > list[j])
38. {
39. temp = list[i];
40. list[i] = list[j];
41. list[j] = temp;
42. }
43. }
44. }
45. }
46.
47. void binary_search(int list[], int lo, int hi, int key)
48. {
49. int mid;
50.

TPGIT/CSE 17
CS8251 Dept of CSE Programming in C

51. if (lo > hi)


52. {
53. printf("Key not found\n");
54. return;
55. }
56. mid = (lo + hi) / 2;
57. if (list[mid] == key)
58. {
59. printf("Key found\n");
60. }
61. else if (list[mid] > key)
62. {
63. binary_search(list, lo, mid - 1, key);
64. }
65. else if (list[mid] < key)
66. {
67. binary_search(list, mid + 1, hi, key);
68. }
69. }}

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 );

TPGIT/CSE 18
CS8251 Dept of CSE Programming in C

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
WhatarePointers?
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.
HowtoUsePointers?
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 );

TPGIT/CSE 19
CS8251 Dept of CSE Programming in C

/* 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
NULLPointers
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

TPGIT/CSE 20
CS8251 Dept of CSE 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.
ImportantNotes:
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’
PointerOperators:
#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
WhatDoesfollowingdeclarationtellscompiler?
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

TPGIT/CSE 21
CS8251 Dept of CSE Programming in C

3. Value at the address contained in ‘ptr’ is integer .


Memory
Declaration Explanation
Required

p is going to store address


1 int *p 2 bytes
of integer value

q is going to store address


2 float *q 2 bytes
of floating value

ch is going to store address


3 char *ch 2 bytes
of character variable

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.
IncrementingaPointer
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++) {

TPGIT/CSE 22
CS8251 Dept of CSE Programming in C

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
Decrementinga 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--) {

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

TPGIT/CSE 23
CS8251 Dept of CSE Programming in C

Address of var[1] = bfedbcd4


Value of var[1] = 100
Address of var[0] = bfedbcd0
Value of var[0] = 10
PointerComparisons
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
3.7 Arrays and Pointers

TPGIT/CSE 24
CS8251 Dept of CSE Programming in C

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];

TPGIT/CSE 25
CS8251 Dept of CSE Programming in C

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;
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

TPGIT/CSE 26
CS8251 Dept of CSE Programming in C

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;

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. */

TPGIT/CSE 27
CS8251 Dept of CSE Programming in C

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>

TPGIT/CSE 28
CS8251 Dept of CSE Programming in C

#include<string.h>
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(strcm
p(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:

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

TPGIT/CSE 29
CS8251 Dept of CSE Programming in C

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

TPGIT/CSE 30
CS8251 Dept of CSE Programming in C

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

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);

TPGIT/CSE 31
CS8251 Dept of CSE Programming in C

return 0;
}
Output of program:

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;
}

TPGIT/CSE 32
CS8251 Dept of CSE Programming in C

Output of program:

TPGIT/CSE 33

You might also like