Dynamic Memory Allocation and Arrays in C
Dynamic Memory Allocation and Arrays in C
1 Flexibility 2 Efficiency
Dynamic memory allocation By allocating only the required
allows programs to request amount of memory, dynamic
and release memory as allocation can optimize
needed, rather than relying on memory usage and
fixed-size data structures. performance.
3 Adaptability
Programs can dynamically adjust their memory usage to handle varying
data sizes and requirements at runtime.
The need for dynamic memory allocation
Variable Data Sizes Memory Constraints Adaptability
Many applications need to work with data Fixed-size data structures can quickly Dynamic allocation allows programs to
of unpredictable or variable size, such as exhaust available memory, especially on adapt to changing requirements and data
user input or external data sources. resource-constrained devices. Dynamic characteristics at runtime, making them
allocation helps manage memory more more flexible and extensible.
efficiently.
The malloc() functions
Allocation Error Handling
The malloc() function dynamically allocates a block of memory Developers must check the return value of malloc() to ensure
of the specified size, returning a pointer to the allocated the allocation was successful, and handle any errors
memory. accordingly.
Deallocation Flexibility
The free() function is used to deallocate memory allocated with Dynamic allocation with malloc() allows for the creation of data
malloc(), preventing memory leaks and ensuring efficient structures of variable size, adapting to the program's needs.
memory management.
1-dimensional arrays in C
1 Declaration
1D arrays in C are declared with a fixed size, such as int
myArray[10];
2 Indexing
Array elements are accessed using zero-based indexing, from 0
to size-1.
Memory Layout
3
1D arrays are stored in contiguous memory locations, allowing
for efficient access and manipulation.
Accessing array elements
Pointer Arithmetic
Array elements can be accessed using pointer arithmetic, such as *(myArray + i).
Index Notation
The more common and intuitive way to access array elements is using the index
notation, like myArray[i].
Bounds Checking
Developers must ensure that array accesses are within the valid bounds of the
array to avoid undefined behavior.
2-dimensional arrays in C
1 Declaration
2D arrays in C are declared with two dimensions, such as int
myArray[3][4];
2 Indexing
2D array elements are accessed using two indices, like
myArray[row][col].
Memory Layout
3
2D arrays are stored in row-major order in contiguous memory
locations.
Dynamically allocating 2D
arrays
Allocate Rows
Allocate Columns
Cleanup