为什么这个联合正在删除c代码中数组中的第一条记录?

这是我的一个头文件,它由一个包含4种不同结构的联合模板组成。

#define MAX 3 union family { struct name /*for taking the name and gender of original member*/ { unsigned char *namess; unsigned int gender; union family *ptr_ancestor; /*this is a pointer to his ancestors details*/ }names; struct male /*for taking the above person's 3 male ancestors details if he is male*/ { unsigned char husb_names[3][20]; unsigned char wife_names[3][20]; unsigned int wife_status[3]; }male_ancestor; struct unmarry /*for taking the above person's 3 female parental ancestors if she is female and unmarried*/ { unsigned int mar; unsigned char parental_fem[3][20]; unsigned int marit_status[3]; }fem_un; struct marry /*for taking 3 parental-in-laws details if she is female and married*/ { unsigned int mar; unsigned char in_law_fem[3][20]; unsigned int in_marit_status[3]; }fem_marr; }; extern union family original[MAX]; /*for original person*/ extern union family ancestor_male[MAX]; /*used if he is male for storing his male ancestor details*/ extern union family ancestor_female[MAX]; /*used if she is female*/ extern int x; 

我的目的是获得一个人的姓名和性别,并根据该人的性别和婚姻状况存储该人的任何3个男/女祖先,如下所示。

我的意思是MAX将有3个成员,每个成员将拥有3个祖先。 这些祖先将由性别决定相应的成员如下条件:

  • 如果男性然后使用struct male
  • 如果女性未婚使用struct unmarry
  • 如果女性结婚使用struct marry

struct name用于我们必须为其取得祖先的成员名称和性别,并将*ptr_ancestor指向相应的祖先数组(ancestormale或ancestorfemale)。

内存中的对象是一个联合。 好。 事实上,我的计划将有一系列的工会。 数组的每个元素可能在联合中使用不同的结构。 在这里我们应该小心分配指针,否则我们可能会在运行时丢失我们的老人记录。

如果可能的话请告诉我如何获得第一个元素的细节即。 original[0]甚至在服用original[1] 。 在这里,我只是获取数组的最后一个元素,所有以前的记录在运行时都消失了。 我没有使用任何其他数据结构或文件。

我的环境是Windows上的Turbo C.

你需要阅读关于工会的这个问题 。 你想要更像的东西:

 struct family { struct name { int gender; int married; blah } names; union { struct male { blah } male_ancestor; struct female_unmarried { blah } female_unmarried_ancestor; struct female_married { blah } female_married_ancestor; }; } 

然后你可以测试family.names.gender和family.names.married来确定要使用的union的哪个成员。

你可能误解了工会的目的。

联合通常用于存储可能是多种forms之一的项目。 例如:

 // Define an array of 20 employees, each identified either by name or ID. union ID { char name[10]; // ID may be a name up to 10 chars... int serialNum; // ... or it may be a serial number. } employees[20]; // Store some data. employees[0].serialNum = 123; strcpy(employees[1].name, "Manoj"); 

structunion之间的关键区别在于struct是多个数据的集合,但union是一个重叠 :您可以只存储其中一个元素,因为它们共享相同的内存。 在上面的示例中, employees[]数组中的每个元素由10个字节组成,这是可以容纳10个char 1个int的最小内存量。 如果引用name元素,则可以存储10个char 。 如果引用serialNum元素,则可以存储1个int (比如4个字节),并且不能访问剩余的6个字节。

所以我认为你想用不同的,独立的结构来代表家庭成员。 你所做的似乎是把几个方形钉子塞进一轮作业。 🙂

高级读者注意事项:请不要提及填充和字对齐。 他们可能会在下学期上学。 🙂

你知道C中的工会意味着什么吗? 你的工会没有3名成员。 你的工会有4名成员。 在这4个成员中,您想要存储多少值?

你为什么不问你的TA?