Friday, March 18, 2022

Structure and Union

 Structure and Union

Introduction of structure,

Ø  Structure is a user-defined datatype in C language which allows us to combine data of different types together.

  • The keyword struct  is used to define a structure.
  • The collection of variables inside the structure are called as members of structure
  • The size of structure can be calculated as the total size of all members used in the structure.
  • To access the members of structure dot ( . ) operator is used, if we are working with pointer structure then points to (->) operator is used.

Declaration & initialization.

The general syntax of structure is

struct name_of_structure

{

   data_type variableName1 / MemberName1

   data_type variableName2 / MemberName2

   data_type variableName3 / MemberName3

   .

   .

   .

   data_type variableNamen / MemberNamen

};

 

Example:

struct Student

{

   int sno;

  char sname[20];

  float avg;

};

In above example struct Student is a structure with sno, sname and avg as members of that structure.

Creating Variable of Structure:

To create variable of structure following statement is used

            struct Student s1;

Initializing the members of structure:

The structure members can be initialize in two different ways

1) struct Student s1 = {12,”Rajesh”,88.9};

2)       struct Student s1;

            s1.sno = 90;

            s1.sname=”Rajesh”;

            s1.avg=88.9;

in above example s1 is a variable / instance of structure student. The members of structure are accessed using dot ( . ) operator.

Programe:

#include<stdio.h>

#include<conio.h>

struct Student

{

    int rno;

    char sname[20];

};

void main()

{

     struct Student s1;

     clrscr();

     printf(“Enter Roll number of Student “);

     scanf(“%d”, &s1.rno);

     printf(“Enter Name of Student “);

     scanf(“%s”, &s1.sname);

     printf(“Roll Number = %d”,s1.rno);

     printf(“\n Name = %s”, s1.sname);

     getch();

}

 

Arrays of Structures:

We can also declare an array of structure variables in which each element of the array will represent a structure variable. 

Example : struct Student s1[5];

The program below defines an array s1 of size 5. Every element of the array s1 is of type Student.

Programe:

#include<stdio.h>

#include<conio.h>

struct Student

{

    int rno;

    char sname[20];

};

void main()

{

     struct Student s1[5];

     int i;

     clrscr();

     for(i=0;i<5;i++)

     {

        printf(“Enter Roll number of Student “);

        scanf(“%d”, &s1[i].rno);

        printf(“Enter Name of Student “);

        scanf(“%s”, &s1[i].sname);

      }

      for(i=0;i<5;i++)

      {

        printf(“Roll Number = %d”,s1[i].rno);

        printf(“\n Name = %s”, s1[i].sname);

      }

       getch();

}

 

Structure within structure

In C, we can declare and place a structure inside another structure. This is also known as nesting of structure; it is also known as Structure within Structure. The declaration is same as the declaration of data type in structure. Structure within structure (or) nesting of structure is used to create complex records.

Example 1:

struct Student

{

    int rno;

    char sname[20];

    struct CollegeDetails

    {

          int collegeNo;

          char collName[20];

     } clg;

};

The above nesting structure can also be written as

struct CollegeDetails

{

    int collegeNo;

    char collName[20];

};

struct Student

{

    int rno;

    char sname[20];

    struct CollegeDetails clg;

};

 

The programe can be written as

#include<stdio.h>

#include<conio.h>

 struct CollegeDetails

{

    int collegeNo;

    char collName[20];

};

 struct Student

{

    int rno;

    char sname[20];

    struct CollegeDetails clg;

};

void main()

{

     struct Student s1;

     clrscr();

     printf(“Enter Roll number of Student “);

     scanf(“%d”, &s1.rno);

     printf(“Enter Name of Student “);

     scanf(“%s”, &s1.sname);

     printf(“Enter College Number “);

     scanf(“%d”, &s1.clg.collegeNo);

     printf(“Enter College Name “);

     scanf(“%s”, &s1.clg.collName);

      printf(“Roll Number = %d”,s1.rno);

     printf(“\n Name = %s”, s1.sname);

     printf(“\n College Number = %d”,s1.clg.collegeNo);

     printf(“\n College Name = %s”, s1.clg.collName);

      getch();

}

 

Introduction to Union.

Ø  A union is a user defined datatype in C programming language.

Ø  It is a collection of variables of different datatypes in the same memory location.

Ø  We can define a union with many members, but at a given point of time only one member can contain a value.

Ø  Union in C language allow data members which are mutually exclusive to share the same memory.

Ø  The size of the union is the size of its largest member because sufficient number of bytes must be reserved to store the largest sized member.

Declaration & initialization

Syntax for declaring a union is same as that of declaring a structure except the keyword struct.

union name_of_union

{

   data_type variableName1 / MemberName1

   data_type variableName2 / MemberName2

   data_type variableName3 / MemberName3

   .

   .

   .

   data_type variableNamen / MemberNamen

};

 

Example:

union Student

{

   int sno;

  char sname[20];

};

 Programe:

#include<stdio.h>

#include<conio.h>

union Day

{

    int dayno;

    char dayname[20];

};

void main()

{

     union Day d1;

     clrscr();

     printf(“Enter Day number “);

     scanf(“%d”, &d1.dayno);

     printf(“\n Day Number is %d”, d1.dayno); // will display day number

     printf(“\n Enter Day Name “);

     scanf(“%s”, &d1.dayname);

     printf(“\n Day Name = %s”,d1.dayname); // will display day name

     printf(“\n Day Number = %d”, s1.dayno);  // will display garbage value

     getch();

}

 

Monday, April 5, 2021

Dynamic Memory Allocation

 Dynamic Memory Allocation

The Dynamic Memory Allocation can be defined as a procedure in which the memory is allocated during the runtime.

 The C language provides some functions to achieve this tasks. These library functions provided by C are defined under <stdlib.h> header file.

The functions are:

1.         malloc()

2.         calloc()

3.         free()

 

The malloc() method:

“malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer which can be cast into a pointer of any form. It initializes each block with default garbage value.

                  Syntax:

ptr = (cast-type*) malloc(byte-size)

For Example:

ptr = (int*) malloc(10 * sizeof(int));

             As the size of int is 2 bytes, this statement will allocate 20 bytes of memory. And, the pointer ptr holds the address of the first byte i.e. base address in the allocated memory.

 Programe 01:

#include<conio.h>

#include<stdio.h>

#include<stdlib.h>

void main()

{

  int i,no,num;

  int *ptr;

  clrscr();

  printf("Enter number of elements to be store ");

  scanf("%d",&no);

  ptr = (int *)malloc(no * sizeof(int));

  for(i=0;i<no;i++)

  {

    printf("Enter %d number ",i+1);

    scanf("%d",&num);

    *ptr = num;

    ptr++;

  }

  for(i=0;i<no;i++)

  {

    ptr--;

    printf("\n Number is %d",*ptr);

 

  }

  getch();

}

Programe 02:

#include<stdio.h>

#include<conio.h>

main()

{

  int no,rd,i;

  int *ptr,*ptr2;

  clrscr();

  printf("Enter how many numbers you want to store.. ");

  scanf("%d",&no);

  ptr = (int *) malloc(no * sizeof(int));

  ptr2 = ptr;

  for(i=0;i<no;i++)

  {

     printf("Enter a number ");

     scanf("%d",&rd);

     *ptr = rd;

     ptr++;

  }

  for(i=0;i<no;i++)

  {

     printf("Numbers are %d\n",*ptr2);

     ptr2++;

  }

  getch();

}

Programe 03:

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

main()

{

  int no,i;

  float num;

  float *ptr, *ptr1;

  clrscr();

  printf("How many number you want to read ");

  scanf("%d",&no);

  ptr = (float *) malloc(no * sizeof(float));

  ptr1 = ptr;

  for(i=0;i<no;i++)

  {

     printf("Enter numbers.. ");

     scanf("%f",&num);

     *ptr = num;

     ptr++;

  }

  for(i=0;i<no;i++)

  {

     printf("\n Number is %f",*ptr1);

     ptr1++;

  }

  getch();

}

Programe 04:

#include <stdio.h>

#include <stdlib.h>

main()

{

    int* ptr;

    int n, i;

 

    n = 5;

    printf("Enter number of elements: %d ", n);

 

    // Dynamically allocate memory using malloc()

    ptr = (int*)malloc(n * sizeof(int));

 

      for (i = 0; i < n; ++i)

       {

            ptr[i] = i + 1;

       }

  

        // Print the elements

        printf("The elements are: ");

        for (i = 0; i < n; ++i)

        {

            printf("%d, ", ptr[i]);

        }

    }

}

  

calloc() method:

The “calloc” or “contiguous allocation” function in C is used to dynamically allocate the specified number of blocks of memory of the specified type. It initializes each memory block with a default value ‘0’.

               Syntax:

ptr = (cast-type*)calloc(n, element-size);

              For Example:

ptr = (float*) calloc(25, sizeof(float));

 This statement allocates contiguous space in memory for 25 elements each with the size of the float. If space is insufficient, allocation fails and returns a NULL pointer.

 Example 01:

#include<stdio.h>

#include<conio.h>

main()

{

  int no,rd,i;

  int *ptr,*ptr2;

  clrscr();

  printf("Enter how many numbers you want to store.. ");

  scanf("%d",&no);

  ptr = (int *) calloc(no, sizeof(int));

  ptr2 = ptr;

  for(i=0;i<no;i++)

  {

     printf("Enter a number ");

     scanf("%d",&rd);

     *ptr = rd;

     ptr++;

  }

  for(i=0;i<no;i++)

  {

     printf("Numbers are %d\n",*ptr2);

     ptr2++;

  }

  getch();

}

 

Example 02:

#include <stdio.h>

#include <stdlib.h>

void main()

{

    int* ptr;

    int n, i;

   // Get the number of elements for the array

    n = 5;

    printf("Enter number of elements: %d", n);

   // Dynamically allocate memory using calloc()

    ptr = (int*)calloc(n, sizeof(int));

       // Get the elements of the array

        for (i = 0; i < n; i++)

       {

            ptr[i] = i + 1;

        }

       // Print the elements of the array

        printf("The elements are: ");

        for (i = 0; i < n; i++)

       {

            printf("%d, ", ptr[i]);

        }

    }

  }

 

 free() method:-

The “free” function in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated by their own. The function free() is used to remove the references/ memory allocated. It helps to reduce wastage of memory by freeing it.

 

Syntax:

free(ptr);

 

 

 Difference between malloc() and calloc() functions:

 

 

malloc()

calloc()

Malloc function contains garbage value.

The memory block allocated by a calloc function is always initialized to zero.

Number of arguments is 1.

Number of argument is 2.

Time efficiency is higher than calloc().

Time efficiency is lower than malloc()

Malloc() function returns only starting address and does not make it zero

Before allocating the address, Calloc() function returns the starting address and make it zero.

It does not perform initializes of memory.

It performs memory initialization.