memory

C Dynamic Memory Allocation

C Dynamic Memory Allocation

In C, dynamic memory allocation allows you to allocate memory at runtime using functions like malloc, calloc, and free.

Using malloc

#include 
#include 

int main() {
    int *ptr;
    ptr = (int*) malloc(5 * sizeof(int));

    if (ptr == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    for (int i = 0; i < 5; i++) {
        ptr[i] = i + 1;
    }

    for (int i = 0; i < 5; i++) {
        printf("Element %d: %d\n", i + 1, ptr[i]);
    }

    free(ptr);
    return 0;
}
    

This program demonstrates how to dynamically allocate memory for an array of integers using malloc, and then free it after use.