Dynamic Memory Allocation
In C, arrays usually have a fixed size, meaning their length must be known at compile time. However, sometimes you need an array whose size is determined at runtime, for example, when reading user input or handling variable-sized data. This is where dynamic memory allocation comes in.
You can use functions from <stdlib.h> like malloc() or calloc() to allocate memory for arrays on the heap instead of the stack. This allows you to create arrays with flexible sizes that can grow or shrink as needed.
main.c
12345678910111213141516171819202122232425262728#include <stdio.h> #include <stdlib.h> int main() { int n; printf("Enter number of elements: "); scanf("%d", &n); // Allocate memory for n integers int *arr = (int*)malloc(n * sizeof(int)); if (arr == NULL) { printf("Memory allocation failed!\n"); return 1; } // Assign values for (int i = 0; i < n; i++) arr[i] = i + 1; // Print values for (int i = 0; i < n; i++) printf("%d ", arr[i]); // Free allocated memory free(arr); return 0; }
Here, malloc() allocates a block of memory large enough to hold n integers. Always check if the pointer returned by malloc() is NULL, it means the allocation failed. After use, free the memory with free() to prevent leaks.
Always pair every malloc() or calloc() with a corresponding free() to avoid memory leaks and wasted system resources.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 9.09
Dynamic Memory Allocation
Swipe to show menu
In C, arrays usually have a fixed size, meaning their length must be known at compile time. However, sometimes you need an array whose size is determined at runtime, for example, when reading user input or handling variable-sized data. This is where dynamic memory allocation comes in.
You can use functions from <stdlib.h> like malloc() or calloc() to allocate memory for arrays on the heap instead of the stack. This allows you to create arrays with flexible sizes that can grow or shrink as needed.
main.c
12345678910111213141516171819202122232425262728#include <stdio.h> #include <stdlib.h> int main() { int n; printf("Enter number of elements: "); scanf("%d", &n); // Allocate memory for n integers int *arr = (int*)malloc(n * sizeof(int)); if (arr == NULL) { printf("Memory allocation failed!\n"); return 1; } // Assign values for (int i = 0; i < n; i++) arr[i] = i + 1; // Print values for (int i = 0; i < n; i++) printf("%d ", arr[i]); // Free allocated memory free(arr); return 0; }
Here, malloc() allocates a block of memory large enough to hold n integers. Always check if the pointer returned by malloc() is NULL, it means the allocation failed. After use, free the memory with free() to prevent leaks.
Always pair every malloc() or calloc() with a corresponding free() to avoid memory leaks and wasted system resources.
Thanks for your feedback!