dynamic memory allocation (theory) in C|| video 22|| normie coder

Поделиться
HTML-код
  • Опубликовано: 28 дек 2024

Комментарии •

  • @danknormie2276
    @danknormie2276  13 часов назад

    //what dynamic memory allocation is:
    // Memory that is allocated during runtime when the program needs it, instead of defining it beforehand.
    // int arr[25];
    // Why Use It?
    // When you don't know how much memory you'll need upfront (e.g., user input, growing arrays, handling files).
    //
    // More efficient memory usage compared to fixed-size arrays.
    // Stack
    // The stack is like a to-do list where temporary variables (e.g., function parameters, local variables) are stored automatically.
    // Fast but has a fixed size and limited memory.
    // Example:
    // c
    // int x = 10; // Stored on the stack
    // Memory is automatically freed when the function ends.
    // Heap
    // The heap is like a warehouse where you can request and release memory as needed (using malloc, calloc, and realloc).
    // Flexible but slightly slower because you manage the memory yourself.
    // Example:
    // c
    // int *ptr = (int *)malloc(10 * sizeof(int)); // Stored on the heap
    // You must free the memory manually with free().
    // Key Difference
    // Stack: Managed automatically, used for short-term storage.
    // Heap: Managed manually, used for dynamic (long-term) memory needs.
    // malloc()
    // Allocates a block of memory of a specified size.
    //
    // int *arr = (int *)malloc(5 * sizeof(int)); // Space for 5 integers
    // Explain how it returns a pointer to the first memory block.
    // int *arr = (int *)malloc(5 * sizeof(int));
    // calloc()
    // Allocates memory and initializes all bytes to 0.
    // int *arr = (int *)calloc(5, sizeof(int)); // Space for 5 integers, all set to 0
    // Mention that it's useful for clean initialization.
    // int *arr = (int *)calloc(5, sizeof(int));
    // realloc()
    // Resizes an already allocated memory block.
    // arr = (int *)realloc(arr, 10 * sizeof(int)); // Resize to hold 10 integers
    // Great for situations where your program grows or shrinks dynamically.
    // arr = (int *)realloc(arr, 10 * sizeof(int));