structure

In the mean time we see how to declare a large number of variable of same data type by array. Now we see how to define different data types in a single variable name. We can do this by structure.

A structure can be imagined as a packet of different data type under a single name.

Syntax:

struct struct-name
{
     data-type variable1;
     data-type variable2;
     data-type variable3;
     data-type variable4;
}tag-name;

Here struct is a keyword.struct-name is as like as variable name. varible1,varible2,varible3,varible4 is under tag-name variable1 can be accessed as follows:
tag-name.variable1;

Code example:

#include<stdio.h>
#include<string.h>
int main()
{
        struct student
        {
              char name[20];
              int roll;
              float mark;
        }info;
 
        printf("Enter name: ");
       scanf("%s",&info.name);
        printf("Enter roll: ");
        scanf("%d",&info.roll);
        printf("Enter mark : ");
        scanf("%f",&info.mark);
 
        printf("\n\n Your input details: \n");
        printf("Name: %s",info.name);
        printf("\nRoll: %d",info.roll);
        printf("\nMark: %f",info.mark);
        return 0;
}

output

Enter roll: 61
Enter mark : 45

Your input details:
Name: Sattar
Roll: 61
Mark: 45.000000

Union

union is exactly same as structure. union keyword is used instead of struct keyword.Now question may arise – what is the difference between structure and union?

Short cut answer is: The deference is in memory allocation.
Explanation: 
In structure, memory space will be created for all members inside structure. An additional padding byte will be added for smaller memory to perfectly align with the longest memory.
In union memory space will be created only for a member which needs largest memory space.
Consider the following code:

struct s_tag
{
   int a;
   long int b;
} x;
union u_tag
{
   int a;
   long int b;
} y;

Here there are two members inside struct and union: int and long int.  Memory space for int is: 4 byte and Memory space for long int is: 8.

So for struct 4+8=12 bytes will be created while 8 bytes will be created for union. This memory allocation can be imagined as follows:

Memory Allocation For struct

a(4 byte)
padding(4 byte)
b (8 byte)

Memory Allocation For union

b (8 byte)

So, actually memory allocation for struct is: 4 byte for ‘a’ + 4 padding byte for align with ‘b’  + 8 byte for ‘b’ = 16 byte

Now we modify the struct as follows:

struct s_tag
{
   int a;
   int b;
   long int c;
} x;

Now Memory Allocation For struct is:

a(4 byte)
b(4 byte)
c (8 byte)

Code example:

#include<stdio.h>
struct s_tag
{
  int a;
  long int b;
} x;
union u_tag
{
     int a;
     long int b;
} y;
int main()
{
    printf("Memory allocation for structure = %d", sizeof(x));
    printf("\nMemory allocation for union = %d", sizeof(y));
    return 0;
}

output

Memory allocation for structure = 16
Memory allocation for union = 8


Next Previous