Techno World Inc - The Best Technical Encyclopedia Online!

THE TECHNO CLUB [ TECHNOWORLDINC.COM ] => C/C++/C# => Topic started by: Taruna on January 03, 2007, 01:46:40 PM



Title: How To Make Efficient C Program Part-II
Post by: Taruna on January 03, 2007, 01:46:40 PM
C supports a special kind of pointer known as void pointer.
It s a generic pointer means it can be used for storing
any type of pointer(int,float,char etc).We can reduce complexity
and number of pointer using void pointer.

We can declare a pointer as void as we declared any
other pointer.E.g-void *ptr;

Advantage:i)Intialistining any pointer of any type.
ii)No type casting is require while intializing.
iii)it s may useful when data type is unknown.
iv)We can assign a void pointer to another non void pointer.

Disadvantage:i)No arithmetic operation is not possible in void pointer.


Use of void pointer-


#include <stdio>
#include<conio>
void call(void *ptr);
/*function prototype*/

void main()
{
float f=90.88;
int i=80;
void *vptr;
clrscr();

printf(" Before Vpointer(integer)=%d",i);
call(&i);
printf(" After Vpointer(integer)=%d",i);

printf(" Before Vpointer=%.2f",f);
call(&f);
printf(" After Vptr=%.2f",f);

getch();
return;
}

void call(void *ptr)
{
char ch;

printf(" Enter the data type(i=integer/f=float)?");
ch=tolower(getch());

if(ch== f )
{
printf(" Enter the value:");
scanf("%f",ptr);
}
else
{
printf(" Enter the value:");
scanf("%d",ptr);
}
}


In the above example a single function(name call) used for taking any type of data.
Here i only accept Float&Integer value.(But you can use any type of data by modifying the function)

But it has a problem i.e for taking any value I used a option e.g(for integer
you have to press i or f for float)as if i used %d in scanf then it only accept integer value or
if i used %f then it only accept only floating value.