CHAPTER 23 / 26

C Dynamic Memory

Learn malloc(), calloc(), realloc() and free() for dynamic memory.

01 — Syntax

int *p = malloc(size);\nfree(p);

02 — Example

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

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

    if (p != NULL) {
        p[0] = 100;
        printf("%d", p[0]);
        free(p);
    }

    return 0;
}

03 — Important Points

04 — Common Mistakes

05 — Real-World Use

Dynamic memory is useful when the amount of data is known only at runtime.

06 — Practice

Create a small program that demonstrates the main idea of C Dynamic Memory.

▶ Try It Yourself← PreviousNext →All Chapters