Dynamic Memory Allocation in C

πŸ“Œ What is Dynamic Memory Allocation?

Dynamic Memory Allocation is the process of allocating memory at runtime using pointers. Unlike static memory allocation, dynamic memory allows the program to request memory from the heap during execution.

🧰 Why Use It?

πŸ“š Functions Used

πŸ’‘ Example Code


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

int main() {
    int *ptr;
    int n;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    // Allocate memory using malloc
    ptr = (int*) malloc(n * sizeof(int));

    // Check if memory is allocated
    if (ptr == NULL) {
        printf("Memory allocation failed!");
        return 1;
    }

    // Use the memory
    for (int i = 0; i < n; i++) {
        ptr[i] = i + 1;
    }

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

    // Free the memory
    free(ptr);

    return 0;
}
    

πŸ“ Explanation

⚠️ Tips