how to create instance of object in C language just like in Java ???

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#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 ???
Last edited on
Put your code inside code tags - makes it a lot easier to read. etc

[ code ]
//Code goes here
[ /code ]

Without the spaces of course - make it easier to read through and help :)
It's my first time and I didn't know that I could do things like that. Thanks for telling me. :D
Just use it like a data type:

person individual;
Sorry but I dun get it. I'm a newbie to programming. Please tell me a little bit more in detail. Thanks in advance
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:
1
2
3
4
5
6
void *array[2];
int a=40;
char *s="Hello, World!\n";
array[0]=(void *)&a;
array[1]=(void *)&s;
std::cout <<*((int *)array[0])<<std::endl<<*((char **)array[1])<<std::endl;
Care must be taken when casting pointers.

To implement data structures, templates are better. They don't exist in C, though. They can be simulated through macros, however.

By the way, your code doesn't work because you're trying to access data that isn't there.
Last edited on
Topic archived. No new replies allowed.