Dynamic Memory Allocation

 Dynamic Memory Allocation


Dynamic memory allocation allows you to allocate memory at runtime using functions like malloc, calloc, and realloc. This is useful when you need to work with variable-sized data structures or manage memory efficiently.



#include <stdio.h>

#include <stdlib.h>


int main() {

    int* numbers = (int*)malloc(5 * sizeof(int)); // Allocate memory for 5 integers


    if (numbers == NULL) {

        printf("Memory allocation failed.\n");

        return 1;

    }


    for (int i = 0; i < 5; i++) {

        numbers[i] = i + 1;

    }


    for (int i = 0; i < 5; i++) {

        printf("%d ", numbers[i]);

    }


    free(numbers); // Release the allocated memory


    return 0;

}

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...