HCL Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
do typecast of void pointer p to the type of which you want to print value, stored in void pointer. eg, if you want to print int value of binary combination represented by void pointer p, then do typecast like, *(int *)p.
#include<stdio.h>
void main()
{
void *p;
int x=10;
float y=20.2;
p=&x;
printf("int %d\n",*(int *)p);
// *(int *)p=20; // useless line
p=&y;
printf("float %g\n",*(float *)p);
}
Cannot dereference the void pointer in printf's
To print you have to use this way,
printf("int %d\n",*(int *)p);
Also for assinging have to assing in this format,
*(float *)p=30.5;
And then print as
printf("float %f\n",*(float *)p);
Note format specifier %f is used, %d will print wrong value.
#include<stdio.h>
void main()
{
int *p;
float *t;
int x=10;
float y=20.2;
p=&x;
printf("int %d\n",*p);
*p=20;
t=&y;
printf("float %f\n",*t);
}
You cannot dereference a void pointer. Cast p in the printf statement to types int and float.
- Shiva August 19, 2013