Dynamic Memory Allocation for Array of Structures in C

Dynamic Memory Allocation of Structure in C Program. 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.

#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

Dynamic Memory Allocation of Structure in C Program

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.

What is Structure in C Program

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. Dynamic memory allocation of structure in C to understand the concept of memory allocation in memory structure in c.

Dynamic Memory Allocation of Structure in C for Malloc

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.

Similar Programs