问题描述
我有以下C程序
#include <stdio.h>
union student{
char name[20];
int id;
float percentage;
}student1;
int main()
{
printf(" Enter name,id and then percentage \n");
scanf("%s",student1.name);
scanf("%d",&student1.id);
scanf("%f",&student1.percentage);
printf("Details of student are:");
printf("Name %s,ID: %d,Percentage: %f",student1.name,student1.id,student1.percentage);
}
输出如下:
Enter name,id and then percentage
Nik
90
7.9
Details of student are:Name ═╠ⁿ@,ID: 1090309325,Percentage: 7.900000
Process returned 0 (0x0) execution time : 7.665 s
Press any key to continue.
问题是为什么这对工会不起作用。
解决方法
这是怎么了。
根据此处的示例,您需要structure,不需要 union。
根据C标准:
- 结构类型描述成员对象的按顺序分配的非空集(在某些情况下,还包括不完整的数组),每个成员对象都有一个可选的指定名称和可能不同的类型。
- 联合类型描述了一组重叠的非空成员对象,每个成员对象都有一个可选的指定名称和可能不同的类型。
换句话说,结构是由一系列成员组成的类型,其存储按有序顺序分配,而联合则是由一系列成员组成的类型,这些成员的存储重叠。
因此,如果必须保留单独的值,则可以使用结构。对于联合而言,成员是重叠的,因此它们没有单独的存储空间来存储可以分别存储和访问的值。
要了解更多信息,请Google输入punning。