× back Need of DS Introduction Types Operations on DS Static vs Dynamic Dynamic memory allocation Programs
Next Topic → ← Previous Topic

Introduction to Data Structure

Need of data structure

Types of Data Structure

Static data structure

  • A structure whose organizational characteristics are invariant throughout its lifetime.
  • Such structures are well supported by high-level languages and familiar examples are arrays and records.

Dynamic data structure

  • A data structure whose organizational characteristics may change during its lifetime.
  • The adaptability afforded by such structures, e.g. linked lists, is often at the expense of decreased efficiency in accessing elements of the structure.

Linear data structure

  • A data structure is said to be linear if its elements form any sequence.
  • There are basicallly two ways of representing such linear structure in memory.
    1. One way is to have the linear relationships between the elements represented by means of sequential memory location. These linear structures are called arrays.
    2. The other way is to have the linear relationship between the elements represented by means of pointers or links. These linear structures are called linked lists. The common examples of linear data structure are arrays, queues, stacks and linked lists.

Non-linear data structure

  • This structure is mainly used to represent data containing a hierarchical relationship between elements. E.g. graphs, family trees and table of contents.

Operations on Data Structures

Static memory and Dynamic memory allocation

Dynamic Memory allocation

Let's quickly brush up the concept of pointers:

  • Pointer is a variable that stores address of another variable.
  • Note: The size of pointer is fixed in a particular system. The size of pointer doesn't depends upon which datatype address it is storing.
  • why we have to write data type before a pointer, for example- int *ptr?
    • The reason for this is that pointers in C and C++ are strongly typed, which means that the data type of the variable being pointed to must match the data type of the pointer itself. This is because pointers are used to store memory addresses, and the size of a memory address can vary depending on the data type of the variable being pointed to.

malloc( ) method

  • The "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 of type void which can be cast into a pointer of any form.
    • The return value is a void pointer to the allocated space. Therefore the void pointer needs to be casted to the appropriate type as per the requirements

Syntax ↓

                       
ptr = (cast-type *) malloc(size of memory)
                       
                   

Example ↓

                       
int *ptr;
ptr = (int *) malloc(100 * sizeof(int));
                        
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory.
And, the pointer ptr holds the address of the first byte in the allocated memory.

we are using sizeof() because in different architecture data-type value changes
                       
                   

Characteristics of malloc function

  • This function returns a pointer to the first byte of the allocated memory block. If the allocation fails, it returns NULL.
  • This function takes a single argument, which is the size of the memory block to be allocated in bytes.
  • The memory allocated by 'malloc()' is not initialized, which means the contents of the block will be undefined until initialized by the program.
  • The memory block allocated by 'malloc()' remains allocated until the program explicitly frees it using the 'free()' function, or until the program terminates.
  • 'malloc()' can be used to allocate memory for variables of any data type, including structures and arrays.
  • 'malloc()' initializes memory with garbage values.

calloc( ) method

Syntax ↓

                       
ptr = (cast-type *) calloc(n, element-size);
here, n is the no. of blocks and element-sze is the size of each element.
                       
                   

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.
                       
                   

realloc( )

Syntax ↓

                       
ptr = realloc(ptr, newSize);
here ptr is reallocated with new size 'newSize'.
                       
                   

free( )

programs

                    
#include <stdio.h>
#include <stdlib.h>

int main()
{
    // use of malloc
    int *ptr;
    int n;
    printf("Enter the size of the array you want to create : ");
    scanf("%d", &n);
    ptr = (int *)malloc(n * sizeof(int)); // create dynamic array of 10 size

    // Check if the memory has been successfully allocated by malloc or not
    if (ptr == NULL)
    {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else
    {
        for (int i = 0; i < n; i++)
        {
            printf("Enter the value no %d of this : ", i);
            scanf("%d", &ptr[i]);
        }

        for (int i = 0; i < n; i++)
        {
            printf("The value %d of this array is %d\n", i, ptr[i]);
        }
    }
    return 0;
}
                    
                
               
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *ptr;
    int n, i;

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

    // Dynamically allocate memory using calloc()
    ptr = (int *)calloc(n, sizeof(int));

    // check if the memory has been successfully allocated by calloc or not
    if (ptr == NULL)
    {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else
    {
        printf("Memory successfully allocated using calloc.\n");
        for (i = 0; i < n; i++)
        {
            ptr[i] = i + 1;
        }

        // print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; i++)
        {
            printf("%d\t", ptr[i]);
        }
    }
    return 0;
}
               
                
                
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *ptr;
    int n, i, previousSize;

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

    // Dynamically allocate memory using calloc()
    ptr = (int *)calloc(n, sizeof(int));

    // check if the memory has been successfully allocated by calloc or not
    if (ptr == NULL)
    {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else
    {
        printf("Memory successfully allocated using calloc.\n");
        for (i = 0; i < n; i++)
        {
            ptr[i] = i + 1;
        }

        // print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; i++)
        {
            printf("%d\t", ptr[i]);
        }
        previousSize = n;
        printf("\nEnter the new size of the array : ");
        scanf("%d", &n);

        // Dynamically re-allocate memory using realloc()
        ptr = realloc(ptr, n * sizeof(int));

        printf("Memory successfully re-allocated using realloc\n");

        // initializing new element array with new value
        for (i = previousSize; i < n; i++)
        {
            ptr[i] = i + 1;
        }
        // print the elements of the array
        printf("The elements of the array after using realloc are: ");
        for (i = 0; i < n; i++)
        {
            printf("%d\t", ptr[i]);
        }
    }
    return 0;
}
                
                
                
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *ptr1, *ptr2;
    int n, i;

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

    // Dynamically allocate memory using malloc()
    ptr1 = (int *)malloc(sizeof(int));

    // Dynamically allocate memory using calloc()
    ptr2 = (int *)calloc(n, sizeof(int));

    // check if the memory has been successfully allocated by calloc or not
    if (ptr1 == NULL || ptr2 == NULL)
    {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else
    {
        printf("Memory successfully allocated using malloc.\n");
        // free ptr1 memory
        free(ptr1);
        printf("Malloc memory successfully freed.\n");

        printf("Memory successfully allocated using calloc.\n");
        // free ptr2 memory
        free(ptr2);
        printf("Calloc memory successfully freed.\n");
    }
    return 0;
}
                
                    

References ↓