×

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.


Related Topics

Threaded Binary Tree

The linked form of binary trees wastes storage capacity because more than half of the connection variables have a Missing value. A binary tree has several nodes. Hence n+1 link fields...

8 minutes read.

Linear vs Non-Linear: Data Structure

What is Linear Data Structure? The data structure is said to be linear if the data elements are arranged linearly or we can say sequentially. In the linear data structure, the...

3 minutes read.

Reverse the Singly Linked List in C

Reverse the Singly Linked List in C This article has given a singly linked list and will reverse the linked list by changing the links between nodes. Example:                         Input:  2 -> 4...

3 minutes read.

AVL tree in data structure c++

AVL tree is generally known as the self-sustained and most balanced tree in the field of a binary search tree. It was also widely known as the height-balanced binary tree....

6 minutes read.

Tim Sort

Tim Sort is a mixture stable arranging calculation that exploits normal examples in information, and uses a mix of an improved Merge sort and Binary Insertion sort alongside an interior...

6 minutes read.

Data structure: Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

4 minutes read.

DFS (Depth-first search) Algorithm: Data Structure

What is DFS (Depth-first search)? The depth first search is a graph traversal algorithm. The idea behind this algorithm is backtracking and it is a kind of recursive algorithm. In the...

3 minutes read.

Sorting Algorithms in Data Structures

A sorting algorithm is used to organize the elements of an array or list. Sorting an array, for example. Unsorted array 572941 Sorted array 124579 We're sorting the array in ascending order right now. This procedure...

4 minutes read.

Function to Create a Copy of Binary Search Tree

Implementation // creating a new hashmap in the language C++ that will help us clone a binary tree with arbitrary pointers.  #include<iostream> #include<unordered_map> using namespace std; /* A given binary tree has a record, a...

9 minutes read.

Optimal binary search tree using dynamic programming

Implementation // We are creating a presentation where we will present a recursive method of the optimal binary search tree problem.  #include <bits/stdc++.h> using namespace std; //creating a utility function that will help us...

9 minutes read.

Horizontal and Vertical Scaling

Being a software engineer, you would have designed a website or application and deployed it on any server. Imagine that the developed application starts getting popular, and many users engage...

6 minutes read.

Red-black Tree in Data Structures?

A type of binary tree which is known as the Red-Black tree, is a specialized and unique tree. What is the urgency or, to be more precise, the necessity of...

10 minutes read.

Linear vs Circular Queue: Data Structure

Difference Between Linear and Circular Queue What is Linear Queue? A linear queue is linear data structure which works on first in first out principle. We can say a linear queue is...

3 minutes read.

Data Structures Algorithms

What is an Algorithm? An algorithm is a sequence of steps used to complete a job or get a desired result. It is similar to programming building elements that let cell...

4 minutes read.

Fundamental of Algorithms

An algorithm is a part of any programming solution or coding. If we have to make a solution then first we have to think of a clear idea about the...

13 minutes read.

Operations of B Tree in C++ Language

B tree tends to be a self-aligning and balancing tree that helps us organise our data and document safely. We know that every data or information in the B tree...

9 minutes read.

Sparse Matrix in Data Structure

Sparse Matrix The sparse matrix is a two-dimensional data object which is made by m rows and n columns, so we can say the number of data values in sparse matrix...

6 minutes read.

Insertion Sort in Data Structures

Insertion Sort in C++ Insertion sort is a sorting algorithm that, in each iteration, installs an unsorted element in its proper position Insertion sort operates in a similar way to how we...

3 minutes read.

Given a Generate all Structurally Unique Binary Search Trees

Implementation // Creating a C++ program that will help us build all the binary search trees for the keys from 1 to n.  #include <bits/stdc++.h> using namespace std; // creating a structure that will...

8 minutes read.

Bubble sort algorithm using Javascript

Sorting is a very useful technique in many algorithms and programs. Basically, sorting operations help us to arrange a set of data in a particular manner. Bubble sort is one...

3 minutes read.