OneMoreError
OneMoreError

Reputation: 7728

Using structures in C - Unable to access values

I am trying to run a simple struct program, which stores the information entered by the user in a structure and then prints it.

However, it is not printing the values appropriately. My code is :

#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;
}

When I run the above program, it doesn't print the name of the employee. Also, it does not correctly print the date of joining. Can someone explain what is the mistake here ?

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 ??**

Upvotes: 1

Views: 65

Answers (1)

haccks
haccks

Reputation: 106012

There is no space allocated for \0 in the character arrays dd, mm and yyyy. You need to change your structure to

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

Otherwise it will invoke undefined behavior.

Upvotes: 4

Related Questions