Data Structures Tutorial

Data Structures Tutorial Asymptotic Notation Structure and Union Array Data Structure Linked list Data Structure Type of Linked list Advantages and Disadvantages of linked list Queue Data Structure Implementation of Queue Stack Data Structure Implementation of Stack Sorting Insertion sort Quick sort Selection sort Heap sort Merge sort Bucket sort Count sort Radix sort Shell sort Tree Traversal of the binary tree Binary search tree Graph Spanning tree Linear Search Binary Search Hashing Collision Resolution Techniques

Misc Topic:

Priority Queue in Data Structure Deque in Data Structure Difference Between Linear And Non Linear Data Structures Queue Operations In Data Structure About Data Structures Data Structures Algorithms Types of Data Structures Big O Notations Introduction to Arrays Introduction to 1D-Arrays Operations on 1D-Arrays Introduction to 2D-Arrays Operations on 2D-Arrays Strings in Data Structures String Operations Application of 2D array Bubble Sort Insertion Sort Sorting Algorithms What is DFS Algorithm What Is Graph Data Structure What is the difference between Tree and Graph What is the difference between DFS and BFS Bucket Sort Dijkstra’s vs Bellman-Ford Algorithm Linear Queue Data Structure in C Stack Using Array Stack Using Linked List Recursion in Fibonacci Stack vs Array What is Skewed Binary Tree Primitive Data Structure in C Dynamic memory allocation of structure in C Application of Stack in Data Structures Binary Tree in Data Structures Heap Data Structure Recursion - Factorial and Fibonacci What is B tree what is B+ tree Huffman tree in Data Structures Insertion Sort vs Bubble Sort Adding one to the number represented an array of digits Bitwise Operators and their Important Tricks Blowfish algorithm Bubble Sort vs Selection Sort Hashing and its Applications Heap Sort vs Merge Sort Insertion Sort vs Selection Sort Merge Conflicts and ways to handle them Difference between Stack and Queue AVL tree in data structure c++ Bubble sort algorithm using Javascript Buffer overflow attack with examples Find out the area between two concentric circles Lowest common ancestor in a binary search tree Number of visible boxes putting one inside another Program to calculate the area of the circumcircle of an equilateral triangle Red-black Tree in Data Structures Strictly binary tree in Data Structures 2-3 Trees and Basic Operations on them Asynchronous advantage actor-critic (A3C) Algorithm Bubble Sort vs Heap Sort Digital Search Tree in Data Structures Minimum Spanning Tree Permutation Sort or Bogo Sort Quick Sort vs Merge Sort

Dynamic memory allocation of structure in C

We can normally store elements of the same datatype with the help of an array in C programming. We can store multiple numbers of elements of a character data type using strings. Still, there is a need in programming where we need to store multiple elements of different data types example when we collect data of students where name is of character data type. The second type of data that a roll number is a number type.

Structures

In order to store multiple elements having different data types, the structure is used. The structure can hold "n" number of elements means any number of elements. Now let us move into syntax.

Syntax

struct structurename
{
datatype ele1;
datatype ele2;
datatype ele3;
datatype ele4;
datatype ele5;
.
.
.
.
};

We always need to start with the “struct” keyword and add the structure name, which can be of the programmer's wish. Next, we need to open the parenthesis and declaration. Finally, close the parenthesis after declaring all elements along with datatypes. Adding a semi-colon at the end is important.

Syntax Example

struct Customer
{
int customerid;
char name[20];
};
main()
{
int a;
Struct Customer c[25];
}

We know that we need to add the data type and then the variable name while declaring variables in the main function. For structure, the data type name will be "struct structurename," which means here it is "struct Customer" and then we need to add a variable name, which is "c" here now, and the memory will be allocated to the variable.

The structure variable always holds the base address, this only points to the datatype, but we don't have a pointer here because it is an internal pointer value.104bytes memory is allocated to the structure variable that is "c" as we have named [100]; each character occupies a 1-byte memory character means 100 bytes for 100 characters, and one integer variable, which is 4 bytes in a 64-bit system, so the total is 104 bytes.

Till here, we stored information now; let us move to access part

Accessing

We can access structures simply using the dot "." operators like “c.customerid” and “c.name”.

We must know how to declare the size of the structure before proceeding.

Size of Structure

By using "sizeof" keyword, we can find the size, sizeof(variable name). We can also use sizeof(struct strcutname).

Check the below example to get a quick idea.

#include<stdio.h>
struct Customer
{
int customerid;
char name[100];
};
void main()
{
struct Customer c;
printf("size of Customer structure is %lu  \n",sizeof(c));
printf("size of Customer is %lu ",sizeof(struct Customer));


}

Output 

Dynamic memory allocation of structure In C

Here we used “%ul” it is for unsigned long or unsigned int; we can also use %d, but the C compiler will show a small warning. Finally, we can pass either variable or datatype name in sizeof().

Dynamic Memory Allocation In C

Each array element is a structure object, and each object has all the details. A base address is assigned to the array. The allocation of 3 elements is like this. To access the customer id of the second customer then, we need to say “c[2].customerid” .If we want to access the name, then s[2].name.

This image shows how memory is allocated to the array of structures

Dynamic memory allocation of structure In C

Example In C

#include <stdio.h>
struct Customer
{
int customerid;
char name[20];
}s[3];
int main()
{  
int i;
for(i;i<3;i++)
{
    printf("Enter the values of id and name \n");
scanf("%d \n %s",&s[i].customerid,&s[i].name);


}
printf("The entered details of all theree customers: \n");


for(int i;i<3;i++)
{
printf("\n %d \n %s \n",s[i].customerid,s[i].name);
}




    return 0;
}

Output

Dynamic memory allocation of structure In C

To display all details, we need to use for loop. Finally we added 3 customers data and print them in the output.

Dynamic memory allocation and dynamic structure

 Dynamic allocation is a fairly unique feature of C (even in high-level languages). This allows you to create data types and structures of any size and length that meet the needs of the program in your program. Let's look at two common uses for this.

Malloc

 The most common use of the malloc function is to try to "get" a contiguous chunk of memory.

 It is defined as:

void * malloc(size_t_number_of_bytes)

That is, it returns a pointer of type void *. This is the beginning of the reserved portion of size number_of_bytes in memory. If memory cannot be allocated, a null pointer is returned.  Since void * is returned, the C standard states that this pointer can be cast to any type. The argument type size_t is defined in stdlib.h and is an unsigned type.

Calloc and Realloc

There are two additional memory allocation functions, Calloc() and Realloc(). Their prototypes are given below:

void *calloc(size_t num_elements, size_t element_size}; 
 
 void *realloc( void *ptr, size_t new_size); 


Malloc does not initialise memory (to zero) in any way. If you wish to initialise memory then use calloc. Calloc is slightly more computationally expensive but, occasionally, more convenient than malloc. Also note the different syntax between calloc and malloc in that calloc takes the number of desired elements, num_elements, and element_size, element_size, as two individual arguments. So, to assign 100 integer elements that are initially all zeros, do the following:

 int * ip; 
 ip = (int *) calloc (100, sizeof (int)); 

Realloc is a function that attempts to resize previously allocated memory blocks. The new size can be large or small. As the block grows, the old content remains and additional storage is added at the end of the block. Reducing the size does not change the rest of the content.

 If the original block cannot be resized, realloc will try to allocate a new block of memory and copy the contents of the old block. Note that as a result, a new pointer (with a different value) is returned. You need to use this new value. If new memory cannot be reallocated, realloc returns NULL.

 Therefore, to change the size of the memory allocated to the * ip pointer above to an array block of integers of 50 instead of 100:

ip = (int *) calloc (ip, 50);

Advantages of structures

1. It is possible to create datatypes with different data types, unlike arrays and strings. For example, if we want to store student records with the students' names, roll numbers, grades, and addresses, the items will have different types. For example, the roll number will have an integer number type, the name will have a string type, the grades will have a floating-point type, and the address will be a string type.

2. It reduces complexity and increases productivity.

3. It eliminates a lot of burden of storing in different files as it is heterogenous.

4. It enhances the maintainability of code

5. It is very much suitable for some mathematical operations also.



ADVERTISEMENT
ADVERTISEMENT