Hi,
I was just going though the forum postings and found many queries on generic pointers. I thought a simple program could be really hepful. Please let me know if its useful.
#include<stdio.h>
#include<conio.h>
void showArray(void *gp,int len,int typ)
{
int i;
switch(typ)
{
case 1: //Treating the address as char.
for (i = 0; i < len; i++)
printf("%c",*((char *)gp+i));
break;
case 2: //Treating the address as int.
for (i = 0; i < len; i++)
printf("%d ",*((int *)gp+i));
break;
case 3://Treating the address as float.
for (i = 0; i < len; i++)
printf("%f ",*((float *)gp+i));
break;
default:
printf("\nThe type requested couldn't be recognized!"
}
}
main()
{
int i_ar[20], i;
char c_ar[5];
float f_ar[5];
clrscr();
printf("\nEnter your short name : "
gets(c_ar);
printf("\n\tHit a key to see the result.\n\n"
getch();
printf("\n Enter 5 numbers of your preference:" );
for(i = 0; i<5; i++)
{
printf("\nEnter number %d : ",i+1);
scanf("%d",&i_ar[ignore][/ignore]);
}
printf("\n Enter 5 floating numbers of your preference:" );
for(i = 0; i<5; i++)
{
printf("\nEnter number %d : ",i+1);
scanf("%f",&f_ar[ignore][/ignore]);
}
printf("\nThe Char array:->\n"
showArray(c_ar,strlen(c_ar), 1);
printf("\nThe Integer array:-I\n"
showArray(i_ar,5, 2);
printf("\nThe Float array:-0\n"
showArray(f_ar,5, 3);
return 0;
}
And yes let me know if you have a better way of doing this. Have fun coding...
Chow!
Jayanta.
mail me : jayantaroy@email.com
I was just going though the forum postings and found many queries on generic pointers. I thought a simple program could be really hepful. Please let me know if its useful.
Code:
/************* FUNCTION OVERLOADING IN C ******************/
#include<conio.h>
void showArray(void *gp,int len,int typ)
{
int i;
switch(typ)
{
case 1: //Treating the address as char.
for (i = 0; i < len; i++)
printf("%c",*((char *)gp+i));
break;
case 2: //Treating the address as int.
for (i = 0; i < len; i++)
printf("%d ",*((int *)gp+i));
break;
case 3://Treating the address as float.
for (i = 0; i < len; i++)
printf("%f ",*((float *)gp+i));
break;
default:
printf("\nThe type requested couldn't be recognized!"
}
}
main()
{
int i_ar[20], i;
char c_ar[5];
float f_ar[5];
clrscr();
printf("\nEnter your short name : "
gets(c_ar);
printf("\n\tHit a key to see the result.\n\n"
getch();
printf("\n Enter 5 numbers of your preference:" );
for(i = 0; i<5; i++)
{
printf("\nEnter number %d : ",i+1);
scanf("%d",&i_ar[ignore][/ignore]);
}
printf("\n Enter 5 floating numbers of your preference:" );
for(i = 0; i<5; i++)
{
printf("\nEnter number %d : ",i+1);
scanf("%f",&f_ar[ignore][/ignore]);
}
printf("\nThe Char array:->\n"
showArray(c_ar,strlen(c_ar), 1);
printf("\nThe Integer array:-I\n"
showArray(i_ar,5, 2);
printf("\nThe Float array:-0\n"
showArray(f_ar,5, 3);
return 0;
}
Code:
/***************** USING GENERIC POINTERS *****************/
Chow!
Jayanta.
mail me : jayantaroy@email.com