Programs on structures and unions in C

Table of Contents

Structure

/*
Author : ITVoyagers (https://itvoyagers.in/)

Date :25th December 2018

Description : Programs on structures and unions.
*/

#include<stdio.h>
#include<conio.h>
#include<string.h>
struct emp
{
    int id;
    char name[10];
    char class;
} s1={1,"enna",'A'};

struct emp s2={2,"meena",'B'};

struct emp s3;

void main()
{
    clrscr();

    s3.id=3;
    strcpy(s3.name,"deeka");
    s3.class='C';

    printf("nAddress of s1n");
    printf("id's address starts from: %d nname's address starts from: %d nclass's address starts from: %dn",&s1.id,&s1.name,&s1.class);

    printf("nValues of s1n");
    printf("id: %d nname: %s nclass: %cn",s1.id,s1.name,s1.class);

    printf("nAddress of s2n");
    printf("id's address starts from: %d nname's address starts from: %d nclass's address starts from: %dn",&s2.id,&s2.name,&s2.class);

    printf("nValues of s2n");
    printf("id: %d nname: %s nclass: %cn",s2.id,s2.name,s2.class);

    printf("nAddress of s3n");
    printf("id's address starts from: %d nname's address starts from: %d nclass's address starts from: %dn",&s3.id,&s3.name,&s3.class);

    printf("nValues of s3n");
    printf("id: %d nname: %s nclass: %cn",s3.id,s3.name,s3.class);
    getch();
}

Output:
Address of s1
id’s address starts from: 4206608
name’s address starts from: 4206612
class’s address starts from: 4206622

Values of s1
id: 1
name: enna
class: A

Address of s2
id’s address starts from: 4206624
name’s address starts from: 4206628
class’s address starts from: 4206638

Values of s2
id: 2
name: meena
class: B

Address of s3
id’s address starts from: 4225552
name’s address starts from: 4225556
class’s address starts from: 4225566

Values of s3
id: 3
name: deeka
class: C

Union

/*
Author : ITVoyagers (https://itvoyagers.in/)

Date :25th December 2018

Description : Programs on structures and unions.
*/

#include<stdio.h>
#include<conio.h>
#include<string.h>
union emp
{
    int id;
    char name[10];
    char class;
};
union emp s1;
void main()
{
    clrscr();
    s1.id=3;
    strcpy(s1.name,"myname");
    s1.class='C';

    printf("nAddress of s1n");
    printf("id's address starts from: %d nname's address starts from: %d nclass's address starts from: %dn",&s1.id,&s1.name,&s1.class);
    printf("nValues of s1n");
    printf("id: %d ->ASCII value for %s nname: %s nclass: %cn",s1.id,s1.name,s1.name,s1.class);
    getch();
}

Output:
Address of s1
id’s address starts from: 4225552
name’s address starts from: 4225552
class’s address starts from: 4225552

Values of s1
id: 1634363715 ->ASCII value for Cyname
name: Cyname
class: C

Leave a Comment