union memory allocation ::存储比分配的内存更多的内容

时间:2014-06-23 05:27:56

标签: c memory-management struct unions

我已将联盟定义为

union person
{
    int roll;
    char fname[10];
    char lname[20];


}p1;

sizeof(p1)= 20个字节。 但是在p1中存储内容时,它会存储超过20个字符。

void main()
{
    printf("\n The size of the union is %zu\t",sizeof(p1));
    printf("\n Enter the details here :\t");
    scanf("%d",&p1.roll);
    scanf("%s",p1.fname);
    scanf("%s",p1.lname);
    printf("\n The union contains are \n");
    printf("\n The roll no is :: \t %d",p1.roll);
    printf("\n The fname is :: \t %s ",p1.fname);
    printf("\n The laname is :: \t %s\n",p1.lname);


}

当我输入超过20个字符时,仍然存储它。

2 个答案:

答案 0 :(得分:3)

  

当我输入超过20个字符时,仍然存储它。

当然是。为什么不呢?你递给scanf一个指针,基本上说'#34;在这里写你想要多少个字符!"

scanf("%9s",p1.fname);
scanf("%19s",p1.lname);

这将阻止scanf超越缓冲区。请注意,我已从每个长度中减去一个,因为scanf也需要编写NUL终止符。

现在,下一个问题:你为什么使用union?联合用于提供相同数据的不同视图。写一个成员有效地破坏了所有其他成员的内容。很少使用union,与struct s。相反。

如果您想存储多个相关信息,请使用struct

struct person
{
    int roll;
    char fname[10];
    char lname[20];
} p1;

答案 1 :(得分:1)

要添加Jonathon的答案,我会指出存储超过20个字符的原因是因为scanf不了解你的联盟。

宣布联盟时

union person
{
    int roll;
    char fname[10];
    char lname[20];

}p1;

并说

scanf("%s",p1.lname);

所有scanf看到的是你有一个char *来存储字符串。它没有看到char[20]

换句话说,p1.lname无法看到您作为程序员知道的其他信息 - scanf只有20个字符。

通常,在C中,作为程序员,您可以确保不会读取或写入比缓冲区可以处理的数据更多的数据。