Saturday 31 August 2013

Pointer and functions | C Programming Language Material pdf



Pointer and functions

1. Pointers can be passed as argument to a function definition.
2. Passing pointers to a function is called call by value.
3. In call by reference what ever changes are made to formal arguments of the function definition will affect the actual arguments in calling function.
4. In call by reference the actual arguments must be pointers or references or addresses.
5. Pointer arguments are use full in functions, because they allow accessing the original data in the calling program.

Ex1: 
void swap (int *, int *);
main ( )
{
int a=10, b=20;
swap(&a, &b); /* a,b are actual parameters */
printf (“ %d %d ”, a ,b);
}
void swap (int *x , int *y) /* x,y are formal parameters */
{
int t;
t = *x;
*x=*y;
*y=t;
}

Output: 20 10

Ex 2:
# include < stdio.h>
# include < conio.h>
void copy (char *, char *);
main ( )
{
char a[20], b[20];
printf (“ enter string a:”);
gets(a);
printf (“ enter string b:”);
gets(b);
printf (“ before copy “ );
printf (“ a=%s and b=%s ”, a , b);
copy(a ,b);
printf (“after copy “);
printf (“ a=%s and b=%s”, a , b);
}
void copy (char *x, char *y)
{
int i=0;
while ((X[i]=Y[i]) != „\0?)
i++;
}

Output: 
enter string a: computer
enter string b: science
before copy
a=computer and b= science
after copy
a=science and b=science

0 comments:

Post a Comment

 

C Programming Language Interview Questions and Answers Tutorial for beginners. Copyright 2013 All Rights Reserved