Mahi Mahi - 14 days ago 5
C Question

Nested Structure Usage in C

From the below given snippet.

typedef struct {
int Code;
int ParentCode;
}TypeStudentConfidential;

typedef struct {
int age;
int RollNo;
int Rank;
char Name[10];
}TypeStudent;

typedef struct {
char class_name[20];
//XXXXXXXXXXXXXXXXX //How could I declare the TypeClass element here?
}TypeClass;

int main()
{

const TypeStudent Stu_Details[] = {
{ 3, 1, 18, "Mahesh"},
{ 3, 1, 7, "Kumar"}
};

const TypeStudentConfidential Conf_Details[] = {
{ 761, 814},
{ 124, 562}
};

const TypeClass Class_Details[]= {
{ "Class 10", Stu_Details}, //struct TypeStudent data
{ "Class 8", Conf_Details} //struct TypeStudentConfidential data
};

return 0;
}


Questions:

1) How to define the XXXXXX marked typedef struct element

2) How to access the XXXXXX marked element from Class_Details

Answer
typedef struct TypeClass {
    char class_name[20];
    struct TypeStudent* type;
} TypeClass;

and to access

Typeclass a = {"classA", NULL};
Typeclass b = {"classB", NULL};
a.type = &b;
printf("%s\n", a.type->class_name); //prints b's classname

Now if you want XXXXXXXXXX to be either a TypeStudent OR TypeStudentConfidential (as your code snippit seems to suggest) you'll probably need to use a union, like so:

#include <stdio.h>


typedef struct TypeClass{
        char class_name[20];
        union type {
                struct TypeStudent* students;
                struct TypeStudentConfidential* studentConfs;
        } type;
} TypeClass;

typedef struct TypeStudent {
        int age;
        int RollNo;
        int Rank;
        char Name[10];
} TypeStudent;

typedef struct TypeStudentConfidential {
        int Code;
        int ParentCode;
} TypeStudentConfidential;

int main() {
        //TypeClass a[2] = {{"C0", {NULL}}, {"C1", {NULL}}};

        TypeStudent studs[2]  = {{10, 10, 10, "Joe"}, {5, 5, 5, "Bob"}};
        TypeStudentConfidential confs[2]  = {{1, 2}, {3, 4}};

        TypeClass a[2] = {{"C0", {.students = studs}}, {"C1", {.studentConfs = confs}}};

        //a[0].type.students = studs;
        //a[1].type.studentConfs = confs;

        printf("%s, %s\n", a[0].type.students->Name, (a[0].type.students + 1)->Name);
        printf("%i, %i\n", a[1].type.studentConfs->Code, (a[1].type.studentConfs + 1)->Code);
        return 0;
}