Reputation: 1399
I have a void array and i want inside it to enter structs.
No i don't mean something like that :
struct pinx
{
int n;
};
struct pinx *array;
I want a dynamic array like that :
struct data
{
void **stack;
}exp1;
To have as members multiple structs like these structs:
struct student
{
char flag;
char name[50];
int sem;
};
struct prof
{
char flag;
char name[50];
int course;
};
Flag is used for telling the program if the array in that specific position has a struct from stud or prof.
Also an image to make it more clear for you.
I tried to connect the array with structs by declaring an array to both of the structs but it doesn't work for both only for one struct.
struct student *student_array;
struct prof *prof_array;
exp1.stack = (void *)student_array;
exp1.stack = (void *)prof_array;
Upvotes: 1
Views: 1140
Reputation: 727137
C provides a union
type for dealing with situations like this. You can define a struct
that "mixes" students and professors, and keeps a flag so that you know which one it is:
struct student {
char name[50];
int sem;
};
struct prof {
char name[50];
int course;
};
struct student_or_prof {}
char flag;
union {
struct student student;
struct prof prof;
}
};
A union
will allocate enough memory to fit any one of its members.
Now you can make an array of student_or_prof
, populate it, and use it to store a mixture of professors and students:
student_or_prof sop[2];
sop[0].flag = STUDENT_TYPE;
strcpy(sop[0].student.name, "quick brown fox jumps");
sop[0].sem = 123;
sop[1].flag = PROF_TYPE;
strcpy(sop[1].prof.name, "over the lazy dog");
sop[1].course = 321;
Upvotes: 3