HCL Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
@dadakhalandhar:
Sorry but did you actually read the question.I was lead to believe that you need to pass an argument to insert() which can take all the the mentioned data types.
insert(void *arg)
{
//you don't know here the type of argument
//so you can typecast it to any type and this
//typecasting can lead to data abort or undesired result
//unless you know beforhand what should i typecast it to??
}
downvoting it.
@aka. you mean to say the following
struct genericStr g;
void insert(void* pa)
{
g.data = pa;
}
void generic()
{
int i = 5;
char c = 'c';
float f = 5.5;
insert(&i);
printf("data is %d\n",*((int *)(g.data)));
insert(&f);
printf("data is %f\n",*((float *)(g.data)));
insert(&c);
printf("data is %c\n",*((char *)(g.data)));
}
So the question is missing a word, "write a generic function API in C so it can ???? any data types..." Did you mean to write "write a generic function API in C so it can hold any data type..."?
I would agree though, not sure how to do that in C, but C++ provides function overloading, so maybe overload the insert() function for each data type to be inserted? That solves the problem of knowing the sizeof the data. Now the insert function can malloc the sizeof the data type and store it in there. However, when you extract the data you would still need to know the type of the data so you know how much data is held, so you might want to add that into the buffer as well.
void insert(void *ptr, char *a)
{
if(strcmp(a,"char")==0)
{
printf("data is %c\n",*((char *)(ptr)));
}
else if(strcmp(a,"int")==0)
{
printf("data is %d\n",*((int *)(ptr)));
}
else
{
printf("data is %f\n",*((float *)(ptr)));
}
}
int main()
{
char a='c';
int b=10;
float c=10.2;
void *ptr=NULL;
ptr=&a;
/*We can acheive the same by finding &sending the sizes of variables and using a switch loop in the insert(), But the sizes vary according to the compilers, which will make the program to function differently when compilers change.*/
insert(ptr , "char");
ptr=&b;
insert(ptr , "int");
ptr=&c;
insert(ptr , "float");
return 0;
}
- dadakhalandhar May 11, 2013