Dynamic memory allocation for structures (malloc) Dry Run in C

Dynamic memory allocation for structures (malloc) is an interactive C dry run visualizer from the Struct Functions Pointers programs section. Study the source code, then use the execution controls to follow each step, variable update, highlighted line, and console output.

This page provides a browser-based dry run with source-code highlighting, auto-scroll, voice narration controls, and execution output for learning the program step by step.

Dynamic memory allocation for structures (malloc) Program Code

#include <stdio.h>
#include <stdlib.h>

struct Item {
    int code;
    char name[50];
    int quantity;
    float price;
};

int main() {
    int n;
    printf("Enter number of items: ");
    scanf("%d", &n);
    
    // Dynamic array of structures
    struct Item *items = (struct Item*)malloc(n * sizeof(struct Item));
    
    if(items == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }
    
    // Input items
    for(int i = 0; i < n; i++) {
        printf("\nItem %d:\n", i+1);
        printf("Code: ");
        scanf("%d", &items[i].code);
        printf("Name: ");
        scanf(" %[^\n]", items[i].name);
        printf("Quantity: ");
        scanf("%d", &items[i].quantity);
        printf("Price: ");
        scanf("%f", &items[i].price);
    }
    
    // Calculate and display total value
    float total = 0;
    printf("\n--- Inventory ---\n");
    for(int i = 0; i < n; i++) {
        float itemTotal = items[i].quantity * items[i].price;
        printf("%s (Code: %d): %d x ₹%.2f = ₹%.2f\n",
               items[i].name, items[i].code, 
               items[i].quantity, items[i].price, itemTotal);
        total += itemTotal;
    }
    printf("Total Inventory Value: ₹%.2f\n", total);
    
    free(items);
    return 0;
}

View the complete Struct Functions Pointers programs page.

Program Console Dynamic memory allocation for structures (malloc) Topic: C Vignaankosh.com
Execution Panel
Step 0/0
Console is empty.