-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamic_memory_allcoation.c
More file actions
30 lines (24 loc) · 1.13 KB
/
dynamic_memory_allcoation.c
File metadata and controls
30 lines (24 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <stdio.h>
#include <stdlib.h> // it is nessary while working with dma
int main()
{
// Dynamic memory allocation is a way to allocate memory to a data strucutures during the runtime. we
int n;
scanf("%d", &n);
// int arr[n]; -> not allowed
// to do things in memory at a very high level we use dma.
// Functioon for dynamic memory allocation
// malloc() - memory allocation- it takes number of bytes to be allocated as an input and returns a pointer of type void.
int *ptr;
ptr = (int *)malloc(n * sizeof(int));
// calloc() - continues allocation - it intialises each memory bloack with a default value of 0
ptr = ptr = (float *)calloc(30, sizeof(float));
// allocates contiguous space in memory for 30 blocks (floats)
// free() - it is used to deallocate the memory
free(ptr);
// realloc() - Sometimes the dynamically allocated memory is insufficient or more than required.
// realloc is used to allocate memory of new size using the previous pointer and size.
ptr = realloc(ptr, newsize);
ptr = realloc(ptr, 3*sizeof(int));
return 0;
}