1

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. enter image description here

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;
3
  • Are you allocating memory anywhere? Do you want to put both objects in the same position? Commented Mar 25, 2014 at 18:55
  • Yes i am allocating memory and no i don't want in the same position i want the one or the other . For exapmple : exp1.stack[0] for student , exp1.stack[1] for professor etc. Commented Mar 25, 2014 at 18:57
  • 1
    In that case you should assign them accordingly. exp1.stack[0] = (void *)student_array; Although, using a union like it is explained in the answer below is better, specially for identical size structures. Commented Mar 25, 2014 at 19:03

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.