我有一个空数组,我想在其中输入结构。
不,我不是那个意思:
struct pinx
{
int n;
};
struct pinx *array;
我想要一个这样的动态数组:
struct data
{
void **stack;
}exp1;
将多个结构作为成员,例如这些结构:
struct student
{
char flag;
char name[50];
int sem;
};
struct prof
{
char flag;
char name[50];
int course;
};
Flag 用于告诉程序该特定位置的数组是否具有来自 stud 或 prof 的结构。
还有一张图片,让您看得更清楚。
我试图通过向两个结构声明一个数组来将数组与结构连接起来,但它只对一个结构不起作用。
struct student *student_array;
struct prof *prof_array;
exp1.stack = (void *)student_array;
exp1.stack = (void *)prof_array;
最佳答案
C 提供了一个union
类型来处理这种情况。您可以定义一个“混合”学生和教授的 struct
,并保留一个标志以便您知道它是哪一个:
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;
}
};
一个 union
将分配足够的内存来容纳它的任何一个成员。
现在您可以制作一个 student_or_prof
数组,填充它,并用它来存储教授和学生的混合:
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;
关于c - 多个结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22643682/