Professional Documents
Culture Documents
ANDHRA PRADESH
Name : Murali Krishna Chintala
Designation : Lecturer in CME
Branch : Computer Engineering
Institute : SUVR & SR GPW, Ethamukkala
Year/Semester : III Semester
Subject : UNIX & C
Subject Code : CM – 304
Topic : Basics of Pointers
Duration : 50 Min
Sub Topic : Parameter passing by reference
Teaching Aids : PPT, Animations
CM304.72 1
Objective
CM304.72 2
Parameter Passing
Call by value.
Call by reference.
CM304.72 3
Call by value
CM304.72 4
Example for call by value
#include<stdio.h>
void fun1(int,int);
main()
{
int x= 10,y=20;
printf(“before calling function x and y are %d%d”,x,y);
fun1(x,y);
printf(“after calling function x and y are %d%d”,x,y);
}
CM304.72 5
Example for call by value
Contd..
CM304.72 6
Output
Before calling function x and y are 10,20.
In function changes are 11,19.
After calling function x and y are 10,20.
The values of x and y are passed to a and b.
But memory locations of x,y and a,b are different.
Hence changes in the values of a,b will not effect x,y.
CM304.72 7
Call by reference
CM304.72 8
Example for call by reference
#include<stdio.h>
void fun(int*,int*);
main()
{
int a=15,b=18;
printf(“before calling function a and b are %d%d\n”,a,b);
fun(&a,&b);
printf(“after calling function a and b are %d%d\n”,a,b);
}
CM304.72 9
Example for call by reference
Contd..
void fun(int*p,int*q)
{
(*p)++;
(*q)--;
printf(“In function changes are “%d%d\n”,*p,*q);
}
CM304.72 10
Output
CM304.72 11
Arrays and Pointers
CM304.72 12
Arrays and Pointers
Contd..
Array name also gives the base address of
the array.
Example:
int x[5];
int *p;
Here the base address of the array is given
by the array name or the ‘0’th element of the
array that is p=x or p=&x[0];
CM304.72 13
Arrays and Pointers
Contd..
When pointer variable ‘p’ is incremented by
p=&x[0];
p+1=&x[1];
p+2=&x[2];
p+3=&x[3];
p+4=&x[4];
CM304.72 14
Arrays and Pointers
Contd..
CM304.72 15
Example program to print Fibonacci
numbers using pointers
#include<stdio.h>
main()
{
int fib[10],i,*f;
fib[0]=0;
fib[i]=1;
for(i=2;i<10;i++)
fib[i]=fib[i-1]+fib[i-2];
CM304.72 16
Example program to print Fibonacci
numbers using pointers
Contd..
f=&fib[0];
for(i=0;i<10;i++)
{
printf(“%d Fibonacci number is %d\n”,i+1,*f);
f=f+1;
}
}/*end of main */
CM304.72 17
Summary
In this class, we have learnt about…
Parameters can be passed in two ways
Call by value
Call by reference
In call by value the values of actual parameters are
passed to the formal parameters.
In call by reference the addresses of the actual
parameters are passed to the formal parameters.
CM304.72 18
Summary
Contd..
CM304.72 19
Quiz
c) both
CM304.72 20
Quiz
c) both
CM304.72 21
Quiz
2.When an array pointer is incremented it refers
a) true
b) false
c) none
CM304.72 22
Quiz
2.When an array pointer is incremented it refers
a) true
b) false
c) none
CM304.72 23
Assignment
CM304.72 24
Frequently Asked Questions
CM304.72 25