Sie sind auf Seite 1von 45

Unit-IV GE6151- COMPUTER PROGRAMMING

UNIT IV FUNCTIONS AND POINTERS


Function – definition of function – Declaration of function – Pass by value – Pass
by reference – Recursion – Pointers - Definition – Initialization – Pointers
arithmetic – Pointers and arrays- Example Problems.
FUNCTION –INTRODUCTION:
 A number of statements grouped into a single logical unit are called a function. The use
of function makes programming easier since repeated statements can be grouped into
functions.
 Splitting the program into separate function make the program more readable and
maintainable.It is necessary to have a single function „main‟ in every C program, along
with other functions used/defined by the programmer.

4.1 TYPES OF FUNCTIONS


1) Predefined standard library functions – such as puts(), gets(),printf(), scanf() etc – These
are the functions which already have a definition in header files (files like stdio.h), so we just call
them whenever needed.
2)User-defined functions are those functions which are defined by the user at the time of
writing program. Functions are made for code reusability and for saving time and space.

Advantages of user defined functions


 User defined functions helps to decompose the large program into small segments which
makes programmer easy to understand, maintain and debug.
 If repeated code occurs in a program. Function can be used to include those codes and
execute when needed by calling that function.

S.KAVITHA /AP/CSE/MSAJCE Page 1 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

 Programmer working on large project can divide the workload by making different
functions.

4.2 PARTS OF THE FUNCTION/ DECLARAION OF FUNCTION:


1. Function declaration
2. Function definition
3. Function call
Function declaration(prototype):
 Function must be declared before it is called. Function prototype gives compiler
information about function name, type of arguments to be passed and return
type.The actual body of the function can be defined separately.
Syntax:
return-type function-name (parameter-list) ;
A function declaration consist of 4 parts.
1. return-type
2. function name
3. parameter list
4. terminating semicolon

Function definition:
Syntax:
return-type function-name (parameter-list)
{

S.KAVITHA /AP/CSE/MSAJCE Page 2 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

function-body ;
}
The first line return-type function-name(parameter) is known as function header and the
statement within curly braces is called function body.
return-type:return type specifies the type of value(int,float,char,double) that function is
expected to return to the program calling the function.
function-name:function name specifies the name of the function. The function name is any valid
C identifier
parameter-list:The parameter list declares the variables that will receive the data sent by calling
program. They often referred to as formal parameters. These parameters are also used to send
values to calling program.
function-body: The function body contains the declarations and the statement necessary for
performing the required task. The body is enclosed within curly braces { } and consists of three
parts.
 local variable declaration
 function statement that performs the tasks of the function
 a return statement that return the value evaluated by the function.
Function call:
 A function call is an expression that passes control and arguments to a function
 When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task and when its return statement is
executed or when its function-ending closing brace is reached, it returns the program
control back to the main program.
 To call a function, you simply need to pass the required parameters along with the
function name, and if the function returns a value, then you can store the returned value.
Example:
/*Program to demonstrate the working of user defined function*/
#include <stdio.h>
int add(int a, int b); //function prototype(declaration)
int main(){
int num1,num2,sum;

S.KAVITHA /AP/CSE/MSAJCE Page 3 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

printf("Enters two number to add\n");


scanf("%d %d",&num1,&num2);
sum=add(num1,num2); //function call
printf("sum=%d",sum);
return 0;
}
int add(int a,int b) //function declarator
{
/* Start of function definition. */
int add;
add=a+b;
return add; //return statement of function
/* End of function definition. */
}
Output:
Enters two number to add
56
sum=11

Return Statement
Return statement is used for returning a value from function definition to calling function.
Syntax:
return (expression);
For example:
return a;
return (a+b);
 In above example, value of variable add in add() function is returned and that value is
stored in variable sum in main() function.
 The data type of expression in return statement should also match the return type of
function.

S.KAVITHA /AP/CSE/MSAJCE Page 4 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

 Suppose that the three functions are stored in three files called main.c, qetline. c, and
strindex. c. Then the command
 cc main.cgetline.cstrindex.c
 compiles the three files, placing the resulting object code in files main.0, qetline.o, and
strindex. 0, then loads them all into an executable file called a. out

4.3 PASSING ARGUMENTS TO FUNCTIONS


 Argument (parameter) refers to data this is passed to function while calling function.
 In above example two variable, num1 and num2 are passed to function during function call
and these arguments are accepted by arguments a and b in function definition.

 Arguments that are passed in function call and arguments that are accepted in function
definition should have same data type.

S.KAVITHA /AP/CSE/MSAJCE Page 5 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

 For example: If argument num1 was of int type and num2 was of float type then, argument
variable a should be of type int and b should be of type float,i.e., type of argument during
function call and function definition should be same.
 A function can be called with or without an argument.
 If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
 Formal parameters behave like other local variables inside the function and are created upon
entry into the function and destroyed upon exit.
 While calling a function, there are two ways in which arguments can be passed to a function

4.3.1 CALL BY VALUE / PASS BY VALUE


 This method copies the actual value of an argument into the formal parameter of the function.
In this case, changes made to the parameter inside the function have no effect on the
argument.
 Consider the function swap() definition as follows.
/* function definition to swap the values */
void swap(int x, int y) {
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
Now, let us call the function swap() by passing actual values as in the following example −
#include <stdio.h>
/* function declaration */
void swap(int x, int y);
int main () {
/* local variable definition */
int a = 100;
int b = 200;

S.KAVITHA /AP/CSE/MSAJCE Page 6 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

printf("Before swap, value of a : %d\n", a );


printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
Output:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
It shows that there are no changes in the values, though they had been changed inside the
function.

4.3.2 CALL BY REFERENCE /PASS BY REFERENCE


 This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This means that
changes made to the parameter affect the argument.
 The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument.
 To pass a value by reference, argument pointers are passed to the functions just like any other
value. Hence, declare the function parameters as pointer types as in the following
function swap(), which exchanges the values of the two integer variables pointed to, by their
arguments.
/* function definition to swap the values */
void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value at address x */

S.KAVITHA /AP/CSE/MSAJCE Page 7 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

*x = *y; /* put y into x */


*y = temp; /* put temp into y */
return;
}
#include <stdio.h>
/* function declaration */
void swap(int *x, int *y);
int main () {
/* local variable definition */
inta,b;
printf("Enter the value of a and b\n");
scanf("%d%d",&a,&b);
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values.
* &a indicates pointer to aie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
Output:
Enter the value of a and b
100
200
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

S.KAVITHA /AP/CSE/MSAJCE Page 8 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

Difference between call by value and call by reference :

No. Call by value Call by reference

1 A copy of value is passed to the function An address of value is passed to the


function

2 Changes made inside the function is not Changes made inside the function is
reflected on other functions reflected outside the function also

3 Actual and formal arguments will be created Actual and formal arguments will be
in different memory location created in same memory location

4.4 SCOPE OF A VARIABLE:


 A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that variable it cannot be accessed.
 There are three places where variables can be declared in C programming language
1. Inside a function or a block which is called local variables.
2. Outside of all functions which is called global variables.
3. In the definition of function parameters which are called formalparameters.
Local Variables
Variables that are declared inside a function or block are called local variables. They can
be used only by statements that are inside that function or block of code. Local variables are not
known to functions outside their own.
Global Variables
 Global variables are defined outside a function, usually on top of the program. Global
variables hold their values throughout the lifetime of your program and they can be accessed
inside any of the functions defined for the program.
 A global variable can be accessed by any function. That is, a global variable is available for
use throughout your entire program after its declaration.
 A program can have same name for local and global variables but the value of local variable
inside a function will take preference.

S.KAVITHA /AP/CSE/MSAJCE Page 9 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

Formal Parameters
 Formal parameters, are treated as local variables with-in a function and they take precedence
over global variables.

4.5 TYPES OF FUNCTIONS BY PASSING ARGUMENTS


There are 4 types of functions in C.
1. Functions with no arguments and no return value.
2. Functions with arguments but no return value.
3. Function with no arguments but with return value.
4. Functions with arguments and with return value.

S.no C function syntax

1 with arguments and with int function ( int ); // function declaration


return values function ( a ); // function call
int function( int a ) // function definition
{
statements;
return a;
}

2 with arguments and without void function ( int ); // function declaration


return values function( a ); // function call
void function( int a ) // function definition
{
statements;
}

S.KAVITHA /AP/CSE/MSAJCE Page 10 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

3 without arguments and without void function(); // function declaration


return values function(); // function call
void function() // function definition
{
statements;
}

4 without arguments and with int function ( ); // function declaration


return values function ( ); // function call
int function( ) // function definition
{
statements;
return a;
}

 If the return data type of a function is “void”, then, it can‟t return any values to the calling
function.
 If the return data type of the function is other than void such as “int, float, double etc”, then,
it can return values to the calling function.
1) Functions with no arguments and no return value in C :

Functions where no arguments will be passed in the function call in the main() and no return
values from the function definition as shown below:
/*Program to demonstrate the working of user defined function*/
#include <stdio.h>
void add(); //function prototype(declaration)
void main(){
add(); //function call
}
void add() //function definition
{
int num1,num2,sum;

S.KAVITHA /AP/CSE/MSAJCE Page 11 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

printf("Enters two number to add\n");


scanf("%d %d",&num1,&num2);
sum=a+b;
printf(“sum=%d”,sum);
}
Output:
Enters two number to add
56
sum=11

2) Functions with arguments and no return value in C :


Functions where formal arguments will be passed in the function call in the main() and no return
values from the function definition as shown below:
/*Program to demonstrate the working of user defined
function*/
#include <stdio.h>
void add(int a, int b); //function prototype(declaration)
void main(){
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
add(num1,num2); //function call
}
void add(int a,int b) //function declarator
{
/* Start of function definition. */
int sum;
sum=a+b;
printf(“sum=%d”,sum);
}

S.KAVITHA /AP/CSE/MSAJCE Page 12 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

Output:
Enters two number to add
56
sum=11

3) Function with no arguments but with return value in C :


Functions where no arguments will be passed in the function call in the main() and some values
will be returned from the function definition as shown below:

/*Program to demonstrate the working of user defined function*/


#include <stdio.h>
int add(); //function prototype(declaration)
void main(){
int sum;
sum=add(); //function call
printf(“sum=%d”,sum);
}
int add() //function definition
{
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
sum=a+b;
return sum;

}
Output:
Enters two number to add
56
sum=11

S.KAVITHA /AP/CSE/MSAJCE Page 13 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

4) Functions with arguments and with return value in C :


Functions where formal arguments will be passed in the function call in the main() and some
values will be returned from the function definition as shown below:
/*Program to demonstrate the working of user defined
function*/
#include <stdio.h>
int add(int a, int b); //function prototype(declaration)
int main(){
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
sum=add(num1,num2); //function call
printf("sum=%d",sum);
return 0;
}
int add(int a,int b) //function declarator
{
/* Start of function definition. */
int add;
add=a+b;
return add; //return statement of function
/* End of function definition. */
}
Output:
Enters two number to add
56
sum=11

4.6 RECURSIVE FUNCTION


 Recursive function is a function which contains a call to itself.
 Recursion can be limited so it does not go out of control.

S.KAVITHA /AP/CSE/MSAJCE Page 14 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

 Recursive functions can be controlled by making sure that there is a safe way to exit them at
some point in the chain of function calls.
 A standard example of controlled recursion is the factorial function. The factorial function is
defined to be the product (multiplication) of all integers from 1 to the parameter of the
function. (The factorial of 0 is 1.)
Here are some examples of the factorial function. (pseudocode )
factorial(3) == 1 * 2 * 3 == 6
factorial(4) == 1 * 2 * 3 * 4 == 24
factorial(3) == 1 * 2 * 3 * 4 * 5 == 120
the factorial function is defined by two equations.
factorial(n) = n * factorial(n-1)
factorial(0) = 1
Code example:
#include <stdio.h>
int factorial (int n)
{
if (n == 0)
return 1;
else
return (n * factorial (n-1));
}

/* To shorten example, not using argp */


int main ()
{
int n;
printf ("Enter the element:\n");
scanf("%d",&n);
printf ("factotial of %d is %d\n",n,factorial(n));
return 0;
}

S.KAVITHA /AP/CSE/MSAJCE Page 15 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

Output:
Enter the element:
3
factotial of 3 is 6
 The main function prints the value of factorial(3). First, the factorial function is called with
the parameter 3. The function tests whether its parameter n is zero.
 It is not, so it takes the else branch if the if statement, which instructs it to return the value
of factorial(3-1). It therefore calls itself recursively with a parameter of 2.
 The new call checks whether its parameter is zero. It isn't (it's 2), so it takes the else branch
again, and tries to calculate 2 * factorial (1).
 In order to do so, it calls itself recursively with a value of 2-1, or 1. The new call checks
whether its parameter is zero.
 It is actually 1, so it takes the else branch again and attempts to calculate 1 * factorial (0). In
order to do so, it calls itself again with the parameter 0.
 Again, the function checks whether its parameter is zero. This time it is, so the function
bottoms out. It takes the first branch of the if statement and returns a value of 1.
 Now the previous function call can also return a value, and so on, until the very first call
to factorial terminates, and the function returns a value of 6.
To sum up, the expression factorial(3) goes through the following steps before finally being
evaluated:
factorial (3) == 3 * factorial(2)
== 3 * (2 * factorial(1))
== 3 * (2 * (1 * factorial(0)))
== 3 * (2 * (1 * 1)))
== 6
Warning of using recursive function:
 Recursive function must have at least one terminating condition that can be satisfied.
 Otherwise, the recursive function will call itself repeatably until the run time stack overflows.

S.KAVITHA /AP/CSE/MSAJCE Page 16 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

4.7 POINTERS - INTRODUCTION:


A pointer is a variable which contains the address of another variable.

 Consider above Diagram which clearly shows pointer concept in c programming –


 i is the name given for particular memory location of ordinary variable.
 Let us consider it‟s Corresponding address be 65624 and the Value stored in variable ‘i’ is 3
 The address of the variable ‘i’ is stored in another integer variable whose name is ‘j’ and
which is having corresponding address 65522
j = &i;
i.e
j = Address of i
Here j is not ordinary variable , It is special variable and called pointer variable as it stores the
address of the another ordinary variable.

Variable Name Variable Value Variable Address

I 5 65524

J 65524 65522
Example :
#include <stdio.h>
void main()
{
int *ptr, i;
i = 11;
/* address of i is assigned to ptr */
ptr = &i;
/* show i's value using ptr variable */
printf("Value of i : %d", *ptr);
}
OUTPUT: Value of i : 11

S.KAVITHA /AP/CSE/MSAJCE Page 17 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

4.8 POINTER DECLARATION:


Syntax:
data_type*pointer_name;
data_type : Type of variable that the pointer points to
Asterisk is called as Indirection Operator
pointer_name: Must be any Valid C identifier
Ways of Declaring Pointer Variable :
int *p;
int * p;
int * p; // all are valid statements
Example of Declaring Integer Pointer :
After declaration memory map will be like this
int i = 5;
int *ptr;

after Assigning the address of variable to pointer , i.e after the execution of this statement
ptr = &i;

Example of Declaring Character Pointer :


charch = 'A';
char *cptr;
Example of Declaring Float Pointer :
floatfvar = 3.14;
float *fptr;
 It is good to initialize the pointer immediately after declaration

S.KAVITHA /AP/CSE/MSAJCE Page 18 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

 & symbol is used to get address of variable


 symbol is used to get value from the address given by pointer.

Pointer storing the address of following DT Pointer is called as

Integer Integer Pointer

Character Character Pointer

Double Double Pointer

Float Float Pointer

 address of variable can be printed using address operator


 „&‟ operator is called as “address of” Operator
 „*‟ is called as „Value at address‟ Operator, also called as „Indirection Operator‟
*(&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.

Program : accessing value and address of Pointer


#include<stdio.h>
main() {
int i = 3, *j, **k;
j = &i;
k = &j;
printf("\nAddress of i = %u", &i);
printf("\nAddress of i = %u", j);
printf("\nAddress of i = %u", *k);
printf("\nAddress of j = %u", &j);

S.KAVITHA /AP/CSE/MSAJCE Page 19 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

printf("\nAddress of j = %u", k);


printf("\nAddress of k = %u", &k);
printf("\nValue of j = %u", j);
printf("\nValue of k = %u", k);
printf("\nValue of i = %d", i);
printf("\nValue of i = %d", *(&i));
printf("\nValue of i = %d", *j);
printf("\nValue of i = %d", **k);
}
Output :
Address of i = 65524
Address of i = 65524
Address of i = 65524
Address of j = 65522
Address of j = 65522
Address of k = 65520
Value of j = 65524
Value of k = 65522
Value of i = 3
Value of i = 3
Value of i = 3
Value of i = 3

Invalid Use of pointer address operator


 We cannot use address operator on the literal to get the address of the literal.
&75
 Only variables have an address associated with them, constant entity does not have
corresponding address.
 we cannot use address operator over character literal
&('a')
Address of expressions

S.KAVITHA /AP/CSE/MSAJCE Page 20 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

(a+b) will evaluate addition of values present in variables and output of (a+b)is nothing but
Literal, so we cannot use Address operator
&(a+b)
 Variable may be integer,character,float but the address of the variable is always integer so
Pointer requires 2 bytes of memory in Turbo C Compiler. This requirement is different for
different Compilers

4.9 INITIALIZE POINTER:


Syntax:
pointer = &variable;

Dereferencing Pointer:
 Asterisk(*) indirection operator is used along with pointer variable while Dereferencing the
pointer variable.
 Asterisk Operator is also called as value at operator
 Dereferencing Operation is performed to access or manipulate data contained in memory
location pointed to by a pointer

Rules for using Pointer :


1. Pointer Variable Can be Assigned the address of another Variable
2. Pointer Variable Can be Assigned the value of another Pointer Variable
int *sptr,*tptr;
sptr = &num;
tptr = sptr;
3. Pointer Variable Can be initialized with zero or NULL value.
int *sptr,*tptr;
sptr = 0;
tptr = NULL;
4. Pointer variable Can Perform Pre/Post fix Increment/Decrement Operation
intarr[20];
int *ptr;

S.KAVITHA /AP/CSE/MSAJCE Page 21 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

ptr = &arr;
ptr++;
5. Integer value can be added or Subtracted from Pointer variable
intarr[20];
int *ptr;
ptr = &arr;
ptr = ptr + 2; //arr[2] will be accessed
6. When two Pointer points to same array then one Pointer variable can be Subtracted from
another
7. Two Pointers pointing to objects of same data type then they can be compared using the
Relational Operator
8. Value cannot be assigned to arbitrary address
int *ptr;
ptr = 100; //Illegal
9. Pointer Variable cannot be multiplied by Constant
int *ptr;
ptr = ptr * 6; //Illegal

C pointer invalid operations


Some more arithmetic operations that cannot be performed on pointer –
 Addition of two addresses.
 Multiplying two addresses.
 Division of two addresses.
 Modulo operation on pointer.
 Cannot perform bitwise AND,OR,XOR operations on pointer.
 Cannot perform NOT operation or negation operation.

Advantages of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees
etc. and used with arrays, structures and functions.
2) We can return multiple values from function using pointer.

S.KAVITHA /AP/CSE/MSAJCE Page 22 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

3) It makes you able to access any memory location in the computer's memory.

Pointer Applications:
1. Passing Parameter by Reference
 Pointer is used to pass parameter to function. In this scheme we are able to modify value
at direct memory location.
2. Accessing Array element
 We can access array using pointer. We can store base address of array in pointer. we can
access each and individual location using pointer.
3. Dynamic Memory Allocation :
 We can use pointer to allocate memory dynamically. Malloc and calloc function is used
to allocate memory dynamically.
4. Reducing size of parameter
 Suppose we want to pass the structure to the function then we can pass structure to the
function using pointer in order to save memory.
5. Passing Strings to function
6. Provides effective way of implementing the different data structures such as tree,graph,linked
list

VOID POINTER:
 Instead of declaring different types of pointer variable it is feasible to declare single pointer
variable which can act as integer pointer, character pointer.
 General Purpose Pointer is called as void Pointer.
 It does not have any data type associated with it
 It can store address of any type of variable

Declaration of Void Pointer :


Syntax:
void * pointer_name;
Example :
void *ptr; // ptr is declared as Void pointer

S.KAVITHA /AP/CSE/MSAJCE Page 23 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

charcnum;
intinum;
floatfnum;
ptr = &cnum; // ptr has address of character data
ptr = &inum; // ptr has address of integer data
ptr = &fnum; // ptr has address of float data
 When we assign address of integer to the void pointer, pointer will become Integer Pointer.
 When we assign address of Character Data type to void pointer it will become Character
Pointer.
 Similarly we can assign address of any data type to the void pointer.
 It is capable of storing address of any data type
 Pointer arithmetic can not be performed in a void pointer.
Example:-
void *ptr;
int a;
ptr=&a;
ptr++; // This statement is invalid and will result in an error because 'ptr' is a void pointer
variable.
take the data pointed to by a void pointer we typecast it with the correct type of the data holded
inside the void pointers location.
#include<stdio.h>
void main()
{
void *ptr; // ptr is declared as Void pointer
charcnum='A';
intinum=10;
floatfnum=2.3;
ptr = &cnum; // ptr has address of character data
printf("char pointer=%c\n",*(char*)ptr);
ptr = &inum; // ptr has address of integer data
printf("Int pointer=%d\n",*(int*)ptr);

S.KAVITHA /AP/CSE/MSAJCE Page 24 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

ptr = &fnum;
printf("float pointer=%f\n",*(float*)ptr);
}
Output:
char pointer=A
Int pointer=10
float pointer=2.300000

4.10 POINTER ARITHMETIC OPERATIONS:


 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 -
 For example: 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 ptr points 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 –

S.KAVITHA /AP/CSE/MSAJCE Page 25 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

#include <stdio.h>
const int MAX = 3;
void 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++;
}
}
OUTPUT:
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;
void main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */

S.KAVITHA /AP/CSE/MSAJCE Page 26 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--) {
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
/* move to the previous location */
ptr--;
}
}
OUTPUT:
Address of var[3] = bfedbcd8
Value of var[3] = 200
Address of var[2] = bfedbcd4
Value of var[2] = 100
Address of var[1] = bfedbcd0
Value of var[1] = 10

Data Initial Address after Required


Operation
Type Address Operations Bytes

int 4000 ++ 4002 2

int 4000 -- 3998 2

char 4000 ++ 4001 1

char 4000 -- 3999 1

float 4000 ++ 4004 4

float 4000 -- 3996 4

long 4000 ++ 4004 4

long 4000 -- 3996 4

We can see address of an variable after performing arithmetic operations.

S.KAVITHA /AP/CSE/MSAJCE Page 27 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

Expression Result

Address + Number Address

Address – Number Address

Address – Address Number

Address + Address Illegal

ADDING INTEGER VALUE WITH POINTER


We can add any integer number to Pointer variable. It is perfectly legal in c programming to add
integer to pointer variable.
The final value is computed by following formulae :
final value = (address) + (number * size of data type)
Consider the following example
int *ptr , n;
ptr = &n ;
ptr = ptr + 3;
Example:
#include<stdio.h>
int main(){
int n=10,m=20;
int *ptr1=&n; //assume address of n as 1000
int *ptr2=&m; //assume address of n as 2000
int x=*ptr1**ptr2;
ptr1=ptr1+3;
printf("Value of x=: %d\n",x);
printf("New Value of ptr : %u",ptr1);
printf("Preincrementof ptr : %u",++ptr1);
return 0;
}
Output :

S.KAVITHA /AP/CSE/MSAJCE Page 28 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

Value of x=: 200


New Value of ptr : 1006
Preincrementofptr : 1008
 Decrementing a pointer to an integer data will cause its value to be decremented by 2

COMPARISON BETWEEN TWO POINTERS :


 Pointer comparison is Valid only if the two pointers are Pointing to same array
 All Relational Operators can be used for comparing pointers of same type
 All Equality and Inequality Operators can be used with all Pointer types
 Pointers cannot be Divided or Multiplied
#include<stdio.h>

int main()
{
inta,b;
int *ptr1,*ptr2;
ptr1 = &a; //assume address of a as 1000
ptr2 = &b; // assume address of b as 2000
if(ptr2 > ptr1)
printf("Ptr2 is far from ptr1");
return(0);
}
Output:
Ptr2 is far from ptr1

MEANING OF (*++ptr) :
Consider the Following Example :
#include<stdio.h>
int main()
{
int n = 20 , *ptr ;

S.KAVITHA /AP/CSE/MSAJCE Page 29 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

ptr = &n;
printf("%d",*++ptr);
return(0);
}
Output :
Garbage Value gets printed
 ‘++’ and ‘*’ both have Equal Precedence
 Associativity is from Right to Left ( Expression evaluated from R->L)
 Both are Unary (Operates on single operand )
 So „ ++ „ is Performed First then „ * „

Calculation of Answer :
* ++ptr= *(++ptr )
= *( 3060 )
= Value Stored at Location 3060
This operation should not be used in normal operation.
Perform this operation if we have consecutive memory i.e Array.
If we perform this operation in above example then we will get garbage value as we dont know
the value stored at 3060.
*++ptr in Array:
#include<stdio.h>
int main()

S.KAVITHA /AP/CSE/MSAJCE Page 30 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

{
intarr[5] = {10,20,30,40,50};
int *ptr ;
ptr = &arr;
printf("%d",*++ptr);
return(0);
}
Output :
20

MEANING OF (++*ptr) POINTER


 ‘++’ and ‘*’ both are having equal precedence and priority. Associativity of these two
operators is from right to left (Expression evaluated from R->L)
 Both the operators are Unary so they will only works on single operand
 Dereference operator „*‟ will get chance for execution before pre increment operator „++‟.
*ptr++ means
 Increment the Pointer not Value Pointed by It
++*ptr means
 ++*ptr Increments the Value being Pointed to by ptr
 Suppose ptr is Pointing to the Integer Variable having value 10. [ num = 10 ]
 Now ++*ptr Results in 11
 *ptr++ means Grab the Value of (*ptr) And then Increment It , which yields again 10
because increment operation will be done in the next statement because it is post increment
operation.
Step by Step Explanation of : ++*ptr
Address of Num : 1000
++*ptr = ++ *ptr
= ++ *(1000)
= ++ (Value at address 1000)
= ++ 10
= 11

S.KAVITHA /AP/CSE/MSAJCE Page 31 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

Step by Step Explanation of : *ptr++


Address of Num : 1000
*ptr++ = *ptr++
= *1000 ++
= Value at address 1000 ++
= 10 ++
= 10
(Post increment will first assign and then do increment)
Example 1 : Consider ++*ptr
#include<stdio.h>
int main()
{
intnum = 10;
int *ptr;

ptr = &num;
printf("Value of ++*ptr : %d",++*ptr);
return(0);
}
Output :
11
Example 2 : Consider *ptr++
#include<stdio.h>
int main()
{
intnum = 10;
int *ptr;
ptr = &num;
printf("Value of *ptr++ : %d", *ptr++);
return(0);
}

S.KAVITHA /AP/CSE/MSAJCE Page 32 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

Output :
10
Hence, ++*ptr and *ptr++ are not same

4.11 DOUBLE POINTER (POINTER TO POINTER):


 A pointer to pointer is a form of multiple indirection, or a chain of pointers. Normally, a
pointer contains the address of a variable.
 When we define a pointer to a pointer, the first pointer contains the address of the second
pointer, which points to the location that contains the actual value as shown below.

 Double (**) is used to denote the double Pointer


 Pointer Stores the address of the Variable
 Double Pointer Stores the address of the Pointer Variable
Declaration :
Syntax: datatype **ptrname;
int **ptr2ptr;
Consider the Following Example :
intnum = 45 , *ptr , **ptr2ptr ;
ptr = &num;
ptr2ptr = &ptr;

What will be the


Statement
Output ?

S.KAVITHA /AP/CSE/MSAJCE Page 33 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

*ptr 45

**ptr2ptr 45

Ptr &n

ptr2ptr &ptr

Example :
#include<stdio.h>
int main()
{
intnum = 45 , *ptr , **ptr2ptr ;
ptr = &num;
ptr2ptr = &ptr;
printf("%d",**ptr2ptr);
return(0);
}
Output :
45
Program :
#include<stdio.h>
#include<conio.h>
void main()
{
int i =50;
int **ptr1;
int *ptr2;
clrscr();
ptr2 = &i;
ptr1 = &ptr2;
printf("\nThe value of **ptr1 : %d",**ptr1);

S.KAVITHA /AP/CSE/MSAJCE Page 34 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

printf("\nThe value of *ptr2 : %d",*ptr2);


getch();
}
Output :
The value of **ptr1 : 50
The value of *ptr2 : 50

 Variable „i‟ is initialized to 50.


 i is stored at Memory Location 2000.
 Pointer Variable „ptr2‟ stores address of variable „i‟.
 *ptr2 will print [Value Stored at Address 2000 ] i.e 50
 Similarly „ptr1‟ is also a pointer variable which stores the address of Pointer variable [i.e ptr2
stores address of integer variable while ptr1 stores address of another pointer variable].
 So **ptr1 is used to access actual value.

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.
#include <stdio.h>
int main () {
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );

S.KAVITHA /AP/CSE/MSAJCE Page 35 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

return 0;
}
OUTPUT:
The value of ptr is 0

4.12 POINTER AND ARRAYS:


 When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array.
 Base address which gives location of the first element is also allocated by the compiler.
Suppose we declare an array arr,
intarr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two byte, the five
element will be stored as follows

Here variable arr will give the base address, which is a constant pointer pointing to the
element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
arr is equal to &arr[0] // by default
We can declare a pointer of type int to point to the array arr.
int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.
we can use that pointer to access the array. Lets have an example,
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]

S.KAVITHA /AP/CSE/MSAJCE Page 36 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

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


{
printf("%d\t", *p);
p++;
}
OUTPUT: 1 2 3 4 5
In the above program, the pointer *p will print all the values stored in the array one by one. We
can also use the Base address (a in above case) to act as pointer and print all the values.
&a[1] is equivalent to (a+1) AND, a[1] is equivalent to *(a+1).
&a[2] is equivalent to (a+2) AND, a[2] is equivalent to *(a+2).
&a[3] is equivalent to (a+1) AND, a[3] is equivalent to *(a+3).
.
.
&a[i] is equivalent to (a+i) AND, a[i] is equivalent to *(a+i).

S.KAVITHA /AP/CSE/MSAJCE Page 37 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

#include <stdio.h>
int main( )
{
/*Pointer variable*/
int *p;
/*Array declaration*/
intval[7] = { 11, 22, 33, 44, 55, 66, 77 } ;
/* Assigning the address of val[0] to pointer: 88820*/
p = &val[0];
for ( int i = 0 ; i <= 6 ; i++ )
{
printf("val[%d]: value is %d and address is %u", i, *p, p);
p++;
}
return 0;
}
OUTPUT:
val[0]: value is 11 and address is 3218280764
val[1]: value is 22 and address is 3218280768
val[2]: value is 33 and address is 3218280772
val[3]: value is 44 and address is 3218280776
val[4]: value is 55 and address is 3218280780
val[5]: value is 66 and address is 3218280784
val[6]: value is 77 and address is 3218280788
Points to Note:
1) Pointer variable data type is same as the type of array – Integer in above example.
2) Pointer has been initialized by array 1st element address(subscript 0 for e.g. &val[0]).
3) In the loop the increment operation(p++) is performed on the pointer variable to get the next
location, this arithmetic is same for all types of arrays (for all data types double, char, int etc..)
even though the bytes consumed by each data type is different.
4) In the above program, the statement p=&val[0], instead we can also use p=val.

S.KAVITHA /AP/CSE/MSAJCE Page 38 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

POINTER LOGIC
You must have understood the logic in above code so now its time to play with few pointer
arithmetic and expressions.
if p = &val[0] which means
*p ==val[0]
(p+1) == &val[2] & *(p+1) == val[2]
(p+2) == &val[3] & *(p+2) == val[3]
(p+n) == &val[n+1) & *(p+n) == val[n+1]
Now its time to rewrite our old example program in a better way –
#include <stdio.h>
int main( )
{
int *p;
intval[7] = { 11, 22, 33, 44, 55, 66, 77 } ;
p = &val[0];
for ( int i = 0 ; i <= 6 ; i++ )
{
printf("val[%d]: value is %d and address is %u", i, *(p+i), (p+i));
}
return 0;
}

POINTER TO MULTIDIMENSIONAL ARRAY


 A multidimensional array is of form, a[i][j]. Lets see how we can make a pointer point to
such an array.
 name of the array gives its base address.
 In a[i][j], a will give the base address of this array, even a+0+0 will also give the base
address, that is the address of a[0][0] element.
Here is the generalized form for using pointer with multidimensional arrays.
*(*(ptr + i) + j) is same as a[i][j]

S.KAVITHA /AP/CSE/MSAJCE Page 39 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

POINTER AND CHARACTER STRINGS


 Pointer can also be used to create strings. Pointer variables of char type are treated as string.
char *str = "Hello";
 This creates a string and stores its address in the pointer variable str.
 The pointer str now points to the first character of the string "Hello". Another important thing
to note that string created using char pointer can be assigned a value at runtime.
char *str;
str = "hello"; //thi is Legal
The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
 Notice that str is pointer to the string, it is also name of the string. Therefore we do not need
to use indirection operator *.

ARRAY OF POINTERS
We can also have array of pointers. Pointers are very helpful in handling character array with
rows of varying length.
char *name[3]={
"Adam",
"chris",
"Deniel"
};
//Now see same array without using pointer
char name[3][20]= {
"Adam",
"chris",
"Deniel"
};

S.KAVITHA /AP/CSE/MSAJCE Page 40 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

4.13 EXAMPLE PROBLEMS:


1. C program to print Prime Numbers Between Two Integers using functions
#include <stdio.h>
intcheckPrimeNumber(int n);
void main()
{
int n1, n2, i, flag;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("Prime numberbers between %d and %d are: ", n1, n2);
for(i=n1+1; i<n2; ++i)
{
// i is a prime number, flag will be equal to 1
flag = checkPrimeNumber(i);

if(flag == 1)
printf("%d ",i);
}
return 0;
}

// user-defined function to check prime number


intcheckPrimeNumber(int n)
{
int j, flag = 1;

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


{
if (n%j == 0)
{
flag =0;

S.KAVITHA /AP/CSE/MSAJCE Page 41 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

break;
}
}
return flag;
}
OUTPUT:
Enter two positive integers: 12
30
Prime numbers between 12 and 30 are: 13 17 19 23 29

2. C program to find maximum of two numbers using function


#include <stdio.h>
/* function declaration */
int max(int num1, int num2);

void main () {
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
}

/* function returning the max between two numbers */


int max(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;

S.KAVITHA /AP/CSE/MSAJCE Page 42 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

else
result = num2;
return result;
}
OUTPUT:
Max value is : 200

3. C program to Add Two Numbers Using Pointer


#include<stdio.h>
void main() {
int *ptr1, *ptr2;
int num;
printf("\nEnter two numbers : ");
scanf("%d %d", ptr1, ptr2);
num = *ptr1 + *ptr2;
printf("Sum = %d", num);
}
OUTPUT:
Enter two numbers : 2 3
Sum = 5

4. Program to Calculate Length of the String using Pointer


#include<stdio.h>
#include<conio.h>
int string_ln(char*);
void main() {
char str[20];
int length;
printf("\nEnter any string : ");
gets(str);

S.KAVITHA /AP/CSE/MSAJCE Page 43 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

length = string_ln(str);
printf("The length of the given string %s is : %d", str, length);
}

int string_ln(char*p) /* p=&str[0] */


{
int count = 0;
while (*p != '\0') {
count++;
p++;
}
return count;
}

OUTPUT:
Enter the String: pritesh
Length of the given string priteshis : 7

5. Write a ‘C’ Program to compute the sum of all elements stored in an array using
pointers
#include<stdio.h>
#include<conio.h>
void main() {
int numArray[10];
int i, sum = 0;
int *ptr;
printf("\nEnter 10 elements : ");
for (i = 0; i < 10; i++)
scanf("%d", &numArray[i]);
ptr = numArray; /* a=&a[0] */
for (i = 0; i < 10; i++) {

S.KAVITHA /AP/CSE/MSAJCE Page 44 of 45


Unit-IV GE6151- COMPUTER PROGRAMMING

sum = sum + *ptr;


ptr++;
}
printf("The sum of array elements : %d", sum);
}
OUTPUT:
Enter 10 elements : 11 12 13 14 15 16 17 18 19 20
The sum of array elements is 155

S.KAVITHA /AP/CSE/MSAJCE Page 45 of 45

Das könnte Ihnen auch gefallen