【问题标题】:union memory allocation :: stores more content than allocated memory联合内存分配 :: 存储的内容多于分配的内存
【发布时间】:2014-06-23 05:27:56
【问题描述】:

我已将联合定义为

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 个字符时,它仍然被存储。

【问题讨论】:

    标签: c memory-management struct unions


    【解决方案1】:

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

    当然是。为什么不呢?你递给scanf 一个指针,基本上说“在这里写尽可能多的字符!”

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

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

    现在,下一个问题:你为什么使用union?联合用于提供相同数据的不同视图。给一个成员写信实际上会破坏所有其他成员的内容。与structs 相比,unions 很少使用。

    如果要存储多条相关信息,请使用struct。

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

    【讨论】:

      【解决方案2】:

      为了补充 Jonathon 的回答,我要指出 原因 存储了 20 多个字符是因为 scanf 不知道您的工会。

      当你声明联合时

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

      然后说

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

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

      换句话说,您作为程序员所知道的附加信息——p1.lname 只有 20 个字符——对scanf 是不可见的。

      通常,在 C 语言中,作为程序员,您需要确保您不会四处读取或写入超出缓冲区可以处理的数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-02
        相关资源
        最近更新 更多