top

Search

C Tutorial

.

UpGrad

C Tutorial

Dynamic Array in C

Introduction to Dynamic-Sized Arrays

Arrays are one of the most fundamental data structures in programming. They store a collection of elements of the same type in a contiguous memory block. However, arrays have a fixed size that must be known at compile time, which limits their flexibility and efficiency.

Dynamic-sized arrays are a solution to this problem. They are arrays that can grow and shrink at runtime, depending on the number of elements inserted or deleted. Dynamic-sized arrays are allocated on the heap, which means they can use any available memory space. They also provide random access to their elements, just like regular arrays. In this blog, we will explore how to create and manipulate dynamic-sized arrays in C using various methods such as malloc, calloc, realloc, VLAs, and flexible array members.

Difference Between Static and Dynamic Array in C

Basis of Difference 

Static Array

Dynamic Array

Size

The size of the array is fixed and must be known at compile time. 

The array size can be changed at runtime and allocated on the heap.

Memory Allocation

The memory for the array is allocated on the stack. 

The memory for the array is allocated using functions like malloc, calloc, or realloc.

Memory Deallocation

The array is automatically deallocated when it goes out of scope. 

The array must be explicitly deallocated using the free function.

Resizing or Reallocating

The array cannot be resized or reallocated. 

The array can be resized or reallocated using the realloc function.

Declaration and Access 

The array can be declared as a local or global variable or as a struct member. 

The array can only be accessed through a pointer variable.

Creation of Dynamic Array in C Using Different Methods

There are different ways to create and manipulate dynamic arrays in C#. Some of the common methods are as follows -

Using malloc() Function 

The malloc() function allocates a block of memory of a given size on the heap. If the allocation fails, it returns a pointer to the allocated memory or NULL. The malloc() function is defined in the <stdlib.h> header file.  

We can use malloc() to create a dynamic array of any type by simply allocating a memory block of some size and then casting the returned void pointer to the pointer of the required type. For example, to create a dynamic array of int with 100 elements, we can write -

int *ptr = (int *)malloc(100 * sizeof(int));

This allocates 100 * sizeof(int) bytes on the heap and assigns the address of the first byte to ptr. We can then access the elements of the array using ptr[i], where i is the index from 0 to 99.  

To free the memory allocated by malloc(), we need to use the free() function and pass the pointer as an argument. For example -

free(ptr);

This releases the memory pointed by ptr and makes it available for other allocations.

Using calloc() Function 

The calloc() function is similar to malloc(), but it has two differences -

  • It takes two arguments: the number of elements and the size of each element. For example, to allocate an array of 100 floats, we can write -

float *ptr = (float *)calloc(100, sizeof(float));
  • It initializes all the allocated memory to zero. This means that all the array elements will have a default value of 0.0.

If the allocation fails, the calloc() function also returns a pointer to the allocated memory or NULL. The calloc() function is also defined in the <stdlib.h> header file.

To free the memory allocated by calloc(), we use the same free() function as for malloc(). For example -

free(ptr);

Resizing Array Using realloc() Function 

The realloc() function changes the size of an existing allocation on the heap. It takes two arguments: a pointer to the old allocation and the new size in bytes. If the reallocation fails, it returns a pointer to the new allocation or NULL.  

If possible, the realloc() function tries to extend or shrink the old allocation in place. If not, it allocates a new block of memory with the new size, copies the old data to it, and frees the old block. The realloc() function is also defined in the <stdlib.h> header file.  

We can use realloc() to resize a dynamic array when we need more or less space for storing elements. For example, suppose we have an array of int with 100 elements allocated by malloc(), and we want to increase its size to 200 elements. We can write -

int *ptr = (int *)malloc(100 * sizeof(int));
// do something with ptr
ptr = (int *)realloc(ptr, 200 * sizeof(int));

This tries to extend the existing allocation pointed by ptr to 200 * sizeof(int) bytes. If successful, ptr will still point to the same address but with more space available for storing elements. If not, ptr will point to a new address with 200 * sizeof(int) bytes allocated, and the old data will be copied there.

Using Variable Length Arrays(VLAs)

Variable length arrays (VLAs) are arrays whose size is determined at runtime but cannot be changed after initialization. They were introduced in the C99 standard but made optional in later versions. They are allocated on the stack and freed automatically when they go out of scope.

We can create a VLA by simply declaring an array with a variable as its size. For example, to create an array of int with n elements, where n is a user input, we can write -

int n;
printf("Enter size of array: ");
scanf("%d", &n);
int arr[n];

This allocates n * sizeof(int) bytes on the stack and creates an array named arr with n elements. We can then access the elements of the array using arr[i], where i is the index from 0 to n-1.

Using Flexible Array Members 

Flexible array members are a special feature of structs in C. They allow us to declare an array as the last member of a struct without specifying its size. This way, we can create a struct with a variable-sized array as its member.  

To create a flexible array member, we need to use an empty bracket [] as the size of the array. For example, to create a struct with an int field and a flexible array of char, we can write -

struct string {
  int length;
  char data[];
};

This defines a struct named string with two members: length and data. The data member is a flexible array of char whose size is not specified.

To allocate memory for a struct with a flexible array member, we need to use malloc() or calloc() and specify the total size of the struct and the array. For example, to create an instance of a string with 10 characters, we can write -

struct string *s = (struct string *)malloc(sizeof(struct string) 10 * sizeof(char));

This allocates sizeof(struct string) 10 * sizeof(char) bytes on the heap and assigns the address to s. We can then access the struct members using s->length and s->data[i], where i is the index from 0 to 9.

Dynamic Allocation of Two-Dimensional Array

Dynamic allocation of a two-dimensional array is a way of creating a matrix of variable size using pointers and memory allocation functions. There are different ways to do this in C, such as -

  • Using a single pointer and a one-dimensional array with pointer arithmetic

  • Using an array of pointers and allocating memory for each row

  • Using a pointer to a pointer and allocating memory for each row 

  • Using a double pointer and one malloc call

Conclusion

we have learned about dynamic arrays in C program and how they can be created and manipulated using different methods. Dynamic arrays are useful data structures that can be initialized with variable size at runtime and resized later in the program. They are allocated on the heap and provide random access to their elements. We have seen how to use malloc(), calloc(), realloc(), and free() function to allocate, initialize, resize, and deallocate memory for dynamic arrays.

FAQs

1. What is a dynamic array in C?

A dynamic array in C++ and C is an array whose size can be changed at runtime and allocated to the heap. A dynamic array can be created using various methods, such as malloc(), calloc(), realloc(), variable length arrays (VLAs), or flexible array members.

2. What are the advantages of dynamic arrays in C? 

Some of the advantages of dynamic arrays in C are - 

  • They can be initialized with variable size at runtime and resized later as needed. 

  • They can save memory by allocating only as much as required.  

  • They can be passed to functions without specifying their size.

3. What are the disadvantages of dynamic arrays in C?

Some of the disadvantages of dynamic arrays in C are -    

  • They require manual memory management using malloc(), free(), and realloc() functions, which can be error-prone and lead to memory leaks or corruption. 

  • They have no bounds checking, so accessing an invalid index can cause undefined behavior or segmentation fault.   

  • They have slower access time than static arrays due to pointer dereferencing and possible cache misses.

Leave a Reply

Your email address will not be published. Required fields are marked *