#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct person
{
char name[20],id[20];
};
int main()
{
struct person individual,*ptr,*retrive;
char name[20],id[20];
int i=0,j=0;
ptr=&individual;
for(;i<2;i++)
{
ptr=(struct person*)malloc(1*sizeof(struct person));
printf("\nEnter the name:");
gets(name);
printf("\nEnter the id:");
gets(id);
strcpy(ptr->name,name);
strcpy(ptr->id,id);
}
//displaying purpose
retrive=&individual;
for(;j<2;j++)
{
printf("\nName : %s",retrive->name);
printf("\nID : %s",retrive->id);
printf("\n");
retrive++;
}
return 0;
}
I run the above code but it's not working as I intended. My purpose is the user can create new person as much as they want (in the above code I only myself limited to only 2 person) anyway. The idea is just like HashMap in java. How can I do something like that in C?? I think for that purpose I should use linked list or something like that but is there any alternative way that I can do something like above ???
C++ is less object-oriented than Java. There's no Object class from which everything else can derive from. If you need something like that, you'll have to implement it yourself.
What C/++ does have, though, are generic pointers (void *), which can be made to point to anything: