Monday, April 14, 2014

Create a structure which can contain any type of data

Generally whenever we create a structure, we define that what kind of data it will be storing. But think it this way, what if you don't know what kind of data structure it can use in future, to avoid that situation. Here is the way :

#include
#include
struct node
{
void *ptr;
struct node *link;
};
int main(void) {
// your code goes here
struct node *head,*temp;
float var = 10.5f;
head = (struct node *)malloc(sizeof(struct node));
*(int *)(head->ptr) =10;
head->link = NULL;

temp = (struct node *)malloc(sizeof(struct node));
*(float *)(temp->ptr) = var;
temp->link = NULL;

head->link = temp;

printf("Value = %d",*(int *)(head->ptr));
printf("Value = %f",*(float *)(temp->ptr));
return 0;
}

Hope it helps you in your next interview :)

No comments: