English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structures

C Language Files

C Others

C Language Reference Manual

C Program Structure Dynamic Memory Allocation

Comprehensive Collection of C Programming Examples

In this example, you will learn to store the information entered by the user using dynamic memory allocation.

To understand this example, you should be familiar with the followingC Programming LanguageTopic:

This program requires the user to store the value of noOfRecords and dynamically allocate memory for the noOfRecords structure variable using the malloc() function.

Demonstration of dynamic memory allocation of structures

#include <stdio.h>
#include <stdlib.h>
struct course {
    int marks;
    char subject[30];
};
int main() {
    struct course *ptr;
    int i, noOfRecords;
    printf("Enter the number of records: ");
    scanf("%d", &noOfRecords);
    //memory allocation for noOfRecords structures
    ptr = (struct course *)malloc(noOfRecords * sizeof(struct course));
    for (i = 0; i < noOfRecords;) ++i) {
        printf("Please enter the subject and mark name:\n");
        scanf("%s %d", (ptr + i)->subject, &(ptr + i)->marks);
    }
    printf("Display information:\n");
    for (i = 0; i < noOfRecords;) ++i)
        printf("%s	%d\n", (ptr + i)->subject, (ptr + i)->marks);
    return 0;
}

Output Results

Enter the number of records: 2
Enter the names of the topic and tag separately:
Programming
22
Enter the names of the topic and tag separately:
Structure
33
Display Information:
Programming      22
Structure        33

Comprehensive Collection of C Programming Examples