c - 在 C 中使用结构 - 无法访问值

标签 c data-structures

我正在尝试运行一个简单的结构程序,它将用户输入的信息存储在一个结构中,然后打印出来。

但是,它没有正确打印值。我的代码是:

#include <stdio.h>
#include <stdlib.h>

struct joining
{
    char dd[2];
    char mm[2];
    char yyyy[4];
};

struct employee
{
    struct joining j;
    char name[50];
    char address[100];
    int id;
};

int main (void)
{
        struct employee e;

        printf ("Enter name :-");
        scanf ("%s",e.name);

        printf ("\n Enter address : ");
        scanf ("%s",e.address);

        printf ("\n Enter id : ");
        scanf ("%d",&e.id);

        printf ("\n  Enter date of joining in dd-mm-yyyy format : ");
        scanf ("%s %s %s",e.j.dd, e.j.mm, e.j.yyyy);

        printf (" Employee id is %d",e.id);   
        printf ("\n Employee name is %s ", e.name);    
        printf ("\n Employee address is %s ",e.address);
        printf ("\n Date of joining is %s %s %s ",e.j.dd,e.j.mm,e.j.yyyy);

    return 0;
}

当我运行上面的程序时,它没有打印员工的姓名。此外,它无法正确打印加入日期。有人可以解释这里的错误是什么吗?

Enter name :- Saurabh
Enter address : India
Enter id : 12
Enter date of joining in dd-mm-yyyy format : 12 03 2014

Employee id is 12
Employee name is                         **// why no output ??**
Employee address is India
Date of joining is 12032014 032014 2014  **// why this output ??**

最佳答案

字符数组ddmmyyyy 中没有为\0 分配空间。您需要将结构更改为

struct joining
{
    char dd[3];
    char mm[3];
    char yyyy[5];
};  

否则它将调用未定义的行为

关于c - 在 C 中使用结构 - 无法访问值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23894816/

相关文章:

Java:如何以极高的性能进行基于位置 (x,y) 的索引?

c - freebsd9下在C中查找硬盘名

将十六进制转换为二进制并将位存储在数组中

c - 错误: Define not done before fetch or execute and fetch

数据库:图像文件作为 blob 还是文件路径?

java - ConcurrentSkipListSet 什么时候有用?

c++ - 指针和指向该指针的地址会导致相同的结果

c++ - gtk 最小尺寸

database - 如何在cosmos db中构建多对多关系

algorithm - 返回给定时间间隔内插入的项目