我正在尝试运行一个简单的结构程序,它将用户输入的信息存储在一个结构中,然后打印出来。
但是,它没有正确打印值。我的代码是:
#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 ??**
最佳答案
字符数组dd
、mm
和yyyy
中没有为\0
分配空间。您需要将结构更改为
struct joining
{
char dd[3];
char mm[3];
char yyyy[5];
};
否则它将调用未定义的行为。
关于c - 在 C 中使用结构 - 无法访问值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23894816/