Home » C Programs » C Program For Dynamic Memory Allocation

C Program For Dynamic Memory Allocation

C Program for dynamic memory allocation. In this program, you can execute the structure for dynamic allocation memory. Using various standard library functions in C, dynamic memory is allocated from the heap.

Malloc() Definition in C

Malloc() and free() are the two most important dynamic memory functions (). The size of the required memory area in bytes is passed to the malloc() function as a single parameter. It returns a pointer to the RAM that was allocated. Malloc function is important method to execute the dynamic memory allocation of structure in c 

Structure Definition in C

In C/C++, a structure is a user-defined data type. A structure provides a data type that can be used to combine objects of potentially disparate types into a single type. Structure is a user-defined datatype in the c programming language that allows us to aggregate data of various sorts. 

Structure aids in the creation of a more meaningful complicated data type. It’s comparable to an Array, however an array only retains data of the same type. Data is stored in the form of records in structure. 

Malloc Function in C Program

In C, the “malloc” or “memory allocation” method is used to allocate a single huge block of memory with the specified size dynamically. It returns a void pointer that can be cast into any type of pointer.

Using various standard library functions in C, dynamic memory is allocated from the heap. Malloc() and free() are the two most important dynamic memory functions (). The size of the required memory area in bytes is passed to the malloc() function as a single parameter. It returns a pointer to the RAM that was allocated. 

c programmers can use dynamic memory allocation to allocate memory at runtime. The various functions that we utilised to dynamically allocate memory at runtime are as follows: At runtime, malloc () allocates a block of memory in bytes. At runtime, calloc () allocates continuous blocks of memory.

C Program For Dynamic Memory Allocation

//C Program For Dynamic Memory Allocation
#include <stdio.h>
#include <stdlib.h>
struct course
{
int marks;
char papers[30];
};
int main()
{
struct course *ptr;
int records;
printf("Enter the number of records");
scanf("%d", &records);
ptr = (struct course *)malloc(records * sizeof(struct course));
for (int i = 0; i < records; ++i) {
printf("Enter the paper and marks\n");
scanf("%s %d", (ptr + i)->papers, &(ptr + i)->marks);
}
printf("Information is \n");
for (int i = 0; i < records; ++i) {
printf("%s\t%d\n", (ptr + i)->papers, (ptr + i)->marks);
}
free(ptr);
return 0;
}

Output:

Enter the number of records2
Enter the paper and marks
maths 45
Enter the paper and marks
science 46
Information is
maths 45
science 46