Dynamic Array In C https://www.skillvertex.com/blog Fri, 10 May 2024 11:39:51 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://www.skillvertex.com/blog/wp-content/uploads/2024/01/favicon.png Dynamic Array In C https://www.skillvertex.com/blog 32 32 Dynamic Array In C https://www.skillvertex.com/blog/dynamic-array-in-c/ https://www.skillvertex.com/blog/dynamic-array-in-c/#respond Fri, 10 May 2024 11:39:51 +0000 https://www.skillvertex.com/blog/?p=3202 Read more]]>

Table of Contents

Dynamic Array In C

A dynamic array in C is a versatile and powerful data structure that provides the flexibility to allocate memory at runtime, allowing for the dynamic resizing of the array during program execution. Unlike static arrays, which have a fixed size determined at compile time, dynamic arrays can adapt to changing requirements, making them an essential tool in C programming for managing and manipulating data efficiently. In this introduction, we’ll explore the concept of dynamic arrays in C, how to create and resize them, and the advantages they offer in terms of memory management and adaptability to varying program needs.

However, we can create a dynamic array with the help of the following methods:

  1. Using malloc() Function
  2. Using calloc() Function
  3. Resizing Array Using realloc() Function
  4. Using Variable Length Arrays(VLAs)
  5. Using Flexible Array Members

1. Dynamic Array Using malloc() Function

  1. Dynamic Memory Allocation: malloc is used to allocate memory at runtime. This is in contrast to static memory allocation, where memory is allocated at compile time, as seen in static arrays.
  2. Memory Size: When you call malloc, you specify the size of the memory block you need in bytes. It allocates a contiguous block of memory of the specified size on the heap.
  3. Return Type: malloc returns a pointer of type void*. This means it can be cast into a pointer of any data type based on your needs. You typically cast it to the appropriate pointer type to work with the allocated memory.
  4. Header File: The malloc function is part of the C standard library and is defined in the <stdlib.h> header file. To use malloc, you need to include this header in your program.

Syntax

ptr = (cast-type*) malloc(byte-size);

Therefore, we can produce a dynamic array of any type by allocating a single block of memory of a particular size and thus typecasting the returned pointer to the pointer of the returned type.

Example

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

Here, they have used a dynamic array of type int and size 100 elements.

Example

// C program to create dynamic array using malloc() function 
  
#include <stdio.h> 
#include <stdlib.h> 
  
int main() 
{ 
  
    // address of the block created hold by this pointer 
    int* ptr; 
    int size; 
  
    // Size of the array 
    printf("Enter size of elements:"); 
    scanf("%d", &size); 
  
    //  Memory allocates dynamically using malloc() 
    ptr = (int*)malloc(size * sizeof(int)); 
  
    // Checking for memory allocation 
    if (ptr == NULL) { 
        printf("Memory not allocated.\n"); 
    } 
    else { 
  
        // Memory allocated 
        printf("Memory successfully allocated using "
               "malloc.\n"); 
  
        // Get the elements of the array 
        for (int j = 0; j < size; ++j) { 
            ptr[j] = j + 1; 
        } 
  
        // Print the elements of the array 
        printf("The elements of the array are: "); 
        for (int k = 0; k < size; ++k) { 
            printf("%d, ", ptr[k]); 
        } 
    } 
  
    return 0; 
}

Output

Enter size of elements:5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,

2. Dynamic Array Using calloc() Function

  • Dynamic Memory Allocation and Initialization: calloc is used to dynamically allocate a specified number of blocks of memory, each of a specified type. Unlike malloc, which does not initialize the memory, calloc initializes each block with a default value of 0. This ensures that the allocated memory is zero-initialized from the start.
  • Function Arguments: The calloc function takes two arguments:
    1. The number of elements required in the dynamic array.
    2. The size of each element in bytes.
  • Memory Allocation: calloc allocates a contiguous block of memory on the heap. The total memory allocated is equal to the number of elements multiplied by the size of each element. The memory block is initialized to zero for each byte.

Syntax

ptr = (cast-type*)calloc(n, element-size);

Example

ptr = (int*) calloc(5, sizeof(float));

The example provided below illustrates how to create a dynamic array using the calloc() method.

Example

// C program to create dynamic array using calloc() function 
  
#include <stdio.h> 
#include <stdlib.h> 
  
int main() 
{ 
  
    // address of the block created hold by this pointer 
    int* ptr; 
    int size; 
  
    // Size of the array 
    printf("Enter size of elements:"); 
    scanf("%d", &size); 
  
    //  Memory allocates dynamically using calloc() 
    ptr = (int*)calloc(size, sizeof(int)); 
  
    // Checking for memory allocation 
    if (ptr == NULL) { 
        printf("Memory not allocated.\n"); 
    } 
    else { 
  
        // Memory allocated 
        printf("Memory successfully allocated using "
               "malloc.\n");
 // Get the elements of the array 
        for (int j = 0; j < size; ++j) { 
            ptr[j] = j + 1; 
        } 
  
        // Print the elements of the array 
        printf("The elements of the array are: "); 
        for (int k = 0; k < size; ++k) { 
            printf("%d, ", ptr[k]); 
        } 
    } 
  
    return 0; 
}

Output

Enter size of elements:6
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 

3. Dynamically Resizing Array Using realloc() Function

In C, the realloc function is used to change the size of previously allocated memory. It’s a way to resize an existing array or create a new one with a different size. This allows your program to adapt to changing memory requirements. The function takes a pointer to the old memory block and the new size in bytes as arguments. It automatically copies the data from the old block to the new one if necessary.

Syntax:

ptr = realloc(ptr, newSize);

Example

/ C program to resize dynamic array using realloc() 
// function 
  
#include <stdio.h> 
#include <stdlib.h> 
  
int main() 
{ 
  
    // address of the block created hold by this pointer 
    int* ptr; 
    int size = 5; 
  
  
    //  Memory allocates dynamically using calloc() 
    ptr = (int*)calloc(size, sizeof(int)); 
  
    if (ptr == NULL) { 
        printf("Memory not allocated.\n"); 
        exit(0); 
    } 
    else { 
        printf("Memory successfully allocated using "
               "calloc.\n"); 
    } 
  
    // inserting elements 
    for (int j = 0; j < size; ++j) { 
        ptr[j] = j + 1; 
    } 
  
    printf("The elements of the array are: "); 
    for (int k = 0; k < size; ++k) { 
        printf("%d, ", ptr[k]); 
    } 
  
    printf("\n"); 
  
    size = 10; 
  
    int *temp = ptr; 
  
    //  using realloc 
    ptr = realloc(ptr, size * sizeof(int)); 
    if (!ptr) { 
        printf("Memory Re-allocation failed."); 
        ptr = temp; 
    } 
    else { 
        printf("Memory successfully re-allocated using "
               "realloc.\n"); 
    } 
  
    // inserting new elements 
    for (int j = 5; j < size; ++j) { 
        ptr[j] = j + 10; 
    } 
  
    printf("The new elements of the array are: "); 
    for (int k = 0; k < size; ++k) { 
        printf("%d, ", ptr[k]); 
    } 
    return 0; 
}

Output

Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5, 
Memory successfully re-allocated using realloc.
The new elements of the array are: 1, 2, 3, 4, 5, 15, 16, 17, 18, 19, 

4. Variable Length Arrays(VLAs)

  • Dynamic Sizing: VLAs in C allow you to determine the size of an array at runtime. This dynamic sizing is useful for situations where the array size is not known until the program is running.
  • Stack Memory Allocation: VLAs allocate memory on the stack, making them local to the scope in which they are defined. The memory is automatically released when the scope ends, which can be advantageous for memory management.
  • Immutable Size: Once you define a VLA with a specific size, you cannot change that size during its lifetime. The size remains fixed.
  • Limitations: Using VLAs has some limitations, such as the potential for stack overflow if the array size is too large, limited portability (as VLAs were introduced in C99 and may not be supported in older compilers), and potential inefficiency for very large arrays.

Example


// C program to demonstrate the use of VLAs 
#include <stdio.h> 
  
int main() 
{ 
  
    int n; 
    printf("Enter the size of the array: "); 
    scanf("%d", &n); 
    
    int arr[n]; 
  
    printf("Enter elements: "); 
  
    for (int i = 0; i < n; ++i) { 
  
        scanf("%d", &arr[i]); 
    } 
      
      printf("Elements of VLA of Given Size: "); 
    for (int i = 0; i < n; ++i) { 
  
        printf("%d ", arr[i]); 
    } 
  
    return 0; 
}

Output

Enter the size of the array: 5
Enter elements: 1 2 3 4 5
Elements of VLA of Given Size: 1 2 3 4 5

5. Flexible Array

Flexible array members in C are arrays defined within a structure without a specific size. Introduced in the C99 standard, they allow for variable-sized arrays in structures. You can control their size using malloc(). A few rules apply: the flexible array member is best placed as the last member of the structure, its size can change at runtime, and the structure must have at least one other named member. Flexible array members are valuable for creating dynamic arrays within structures, often used in data structures like queues and stacks.

Refer the structure given below for example

struct student
{
  int len;
  int 
};

Then, we can use the malloc() function to allocate memory:

struct student *s = malloc(sizeof(*s) + 5 * sizeof(int));

Example

// C program to demonstrate the use of Flexible Array Member 
#include <stdio.h> 
#include <stdlib.h> 
  
// defining struct 
typedef struct { 
    int len; 
    int arr[]; 
} fam; 
  
int main() 
{ 
    // creating an array member of size 5 
    fam* fam1 
        = (fam*)malloc(sizeof(fam*) + 5 * sizeof(int)); 
  
    // creating an array mebmer of size 10 
    fam* fam2 
        = (fam*)malloc(sizeof(fam*) + 10 * sizeof(int)); 
      
    // inserting elements 
    for (int i = 0; i < 5; i++) { 
        fam1->arr[i] = i + 1; 
    } 
    for (int i = 0; i < 10; i++) { 
        fam2->arr[i] = i + 10; 
    } 
  
    //  printing elements 
    printf("Array of Size 5:\n"); 
    for (int i = 0; i < 5; i++) { 
        printf("%d, ", fam1->arr[i]); 
    } 
    printf("\n"); 
  
    printf("Array of size 10:\n"); 
    for (int i = 0; i < 10; i++) { 
        printf("%d, ", fam2->arr[i]); 
    } 
    return 0; 
}

Output

Array of Size 5:
1, 2, 3, 4, 5, 
Array of size 10:
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,

Dynamic Allocation of Two-Dimensional Array

Creating a two-dimensional dynamic array in c.  These are the various methods inorder to produce a 2D dynamic array.

  1. Using a single pointer and a 1D array with pointer arithmetic
  2. Using an array of pointers 
  3. Using a pointer to a pointer 
  4. Using a double-pointer and one malloc call 
  5. Using a pointer to Variable Length Array
  6. Using a pointer to the first row of VLA

FAQ- Dynamic Array In C

Q1. What is a dynamic array in C?

Ans. Dynamic arrays in C are a valuable data structure that enables the creation and manipulation of arrays with flexible sizes during program execution. They are implemented using pointers and memory allocation functions, which optimizes memory usage and helps in building efficient programs. This flexibility and memory efficiency make dynamic arrays a powerful tool in programming.

Q2.What is the syntax of dynamic array in C?

Ans. printf(“Enter size of elements:”); scanf(“%d”, &size); //

Q3. How to use dynamic array in class?

Ans.
Create a new array of the desired size.
Copy data from the old array to the new one.
Delete the old array to avoid memory waste.
Make sure your pointer points to the new array.
These steps help you resize a dynamic array efficiently.


Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/dynamic-array-in-c/feed/ 0