{"id":3202,"date":"2024-05-10T11:39:51","date_gmt":"2024-05-10T11:39:51","guid":{"rendered":"https:\/\/www.skillvertex.com\/blog\/?p=3202"},"modified":"2024-05-10T11:39:51","modified_gmt":"2024-05-10T11:39:51","slug":"dynamic-array-in-c","status":"publish","type":"post","link":"https:\/\/www.skillvertex.com\/blog\/dynamic-array-in-c\/","title":{"rendered":"Dynamic Array In C"},"content":{"rendered":"\n<div class=\"wp-block-rank-math-toc-block\" id=\"rank-math-toc\" id=\"rank-math-toc\"><p>Table of Contents<\/p><nav><ul><li ><a href=\"#dynamic-array-in-c\">Dynamic Array In C<\/a><\/li><li ><a href=\"#1-dynamic-array-using-malloc-function\">1. Dynamic Array Using malloc() Function<\/a><\/li><li ><a href=\"#2-dynamic-array-using-calloc-function\">2. Dynamic Array Using calloc() Function<\/a><\/li><li ><a href=\"#3-dynamically-resizing-array-using-realloc-function\">3. Dynamically Resizing Array Using realloc() Function<\/a><\/li><li ><a href=\"#4-variable-length-arrays-vl-as\">4. Variable Length Arrays(VLAs)<\/a><\/li><li ><a href=\"#5-flexible-array\">5. Flexible Array<\/a><\/li><li ><a href=\"#dynamic-allocation-of-two-dimensional-array\">Dynamic Allocation of Two-Dimensional Array<\/a><\/li><li ><a href=\"#\"> <\/a><\/li><\/ul><\/nav><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"dynamic-array-in-c\">Dynamic Array In C<\/h2>\n\n\n\n<p>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&#8217;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.<\/p>\n\n\n\n<p>However,  we can create a dynamic array with the help of the following methods:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Using malloc() Function<\/strong><\/li>\n\n\n\n<li><strong>Using calloc() Function<\/strong><\/li>\n\n\n\n<li><strong>Resizing Array Using realloc() Function<\/strong><\/li>\n\n\n\n<li><strong>Using Variable Length Arrays(VLAs)<\/strong><\/li>\n\n\n\n<li><strong>Using Flexible Array Members<\/strong><\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-dynamic-array-using-malloc-function\">1. Dynamic Array Using malloc() Function<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Dynamic Memory Allocation<\/strong>: <code>malloc<\/code> 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.<\/li>\n\n\n\n<li><strong>Memory Size<\/strong>: When you call <code>malloc<\/code>, 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.<\/li>\n\n\n\n<li><strong>Return Type<\/strong>: <code>malloc<\/code> returns a pointer of type <code>void*<\/code>. 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.<\/li>\n\n\n\n<li><strong>Header File<\/strong>: The <code>malloc<\/code> function is part of the C standard library and is defined in the <code>&lt;stdlib.h&gt;<\/code> header file. To use <code>malloc<\/code>, you need to include this header in your program.<\/li>\n<\/ol>\n\n\n\n<p>Syntax<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ptr = (cast-type*) malloc(byte-size);\n<\/code><\/pre>\n\n\n\n<p>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.<\/p>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ptr = (int*) malloc(100 * sizeof(int));\n<\/code><\/pre>\n\n\n\n<p>Here, they have used a dynamic array of type&nbsp;<strong>int&nbsp;<\/strong>and size&nbsp;<strong>100 elements.<\/strong><\/p>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C program to create dynamic array using malloc() function \n  \n#include &lt;stdio.h&gt; \n#include &lt;stdlib.h&gt; \n  \nint main() \n{ \n  \n    \/\/ address of the block created hold by this pointer \n    int* ptr; \n    int size; \n  \n    \/\/ Size of the array \n    printf(\"Enter size of elements:\"); \n    scanf(\"%d\", &amp;size); \n  \n    \/\/  Memory allocates dynamically using malloc() \n    ptr = (int*)malloc(size * sizeof(int)); \n  \n    \/\/ Checking for memory allocation \n    if (ptr == NULL) { \n        printf(\"Memory not allocated.\\n\"); \n    } \n    else { \n  \n        \/\/ Memory allocated \n        printf(\"Memory successfully allocated using \"\n               \"malloc.\\n\"); \n  \n        \/\/ Get the elements of the array \n        for (int j = 0; j &lt; size; ++j) { \n            ptr&#91;j] = j + 1; \n        } \n  \n        \/\/ Print the elements of the array \n        printf(\"The elements of the array are: \"); \n        for (int k = 0; k &lt; size; ++k) { \n            printf(\"%d, \", ptr&#91;k]); \n        } \n    } \n  \n    return 0; \n}<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Enter size of elements:5\nMemory successfully allocated using malloc.\nThe elements of the array are: 1, 2, 3, 4, 5,<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-dynamic-array-using-calloc-function\">2. Dynamic Array Using calloc() Function<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Dynamic Memory Allocation and Initialization<\/strong>: <code>calloc<\/code> is used to dynamically allocate a specified number of blocks of memory, each of a specified type. Unlike <code>malloc<\/code>, which does not initialize the memory, <code>calloc<\/code> initializes each block with a default value of 0. This ensures that the allocated memory is zero-initialized from the start.<\/li>\n\n\n\n<li><strong>Function Arguments<\/strong>: The <code>calloc<\/code> function takes two arguments:\n<ol class=\"wp-block-list\">\n<li>The number of elements required in the dynamic array.<\/li>\n\n\n\n<li>The size of each element in bytes.<\/li>\n<\/ol>\n<\/li>\n\n\n\n<li><strong>Memory Allocation<\/strong>: <code>calloc<\/code> 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.<\/li>\n<\/ul>\n\n\n\n<p>Syntax<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ptr = (cast-type*)calloc(n, element-size);\n<\/code><\/pre>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ptr = (int*) calloc(5, sizeof(float));\n<\/code><\/pre>\n\n\n\n<p>The example provided below illustrates how to create a dynamic array using the calloc() method.<\/p>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C program to create dynamic array using calloc() function \n  \n#include &lt;stdio.h&gt; \n#include &lt;stdlib.h&gt; \n  \nint main() \n{ \n  \n    \/\/ address of the block created hold by this pointer \n    int* ptr; \n    int size; \n  \n    \/\/ Size of the array \n    printf(\"Enter size of elements:\"); \n    scanf(\"%d\", &amp;size); \n  \n    \/\/  Memory allocates dynamically using calloc() \n    ptr = (int*)calloc(size, sizeof(int)); \n  \n    \/\/ Checking for memory allocation \n    if (ptr == NULL) { \n        printf(\"Memory not allocated.\\n\"); \n    } \n    else { \n  \n        \/\/ Memory allocated \n        printf(\"Memory successfully allocated using \"\n               \"malloc.\\n\");\n \/\/ Get the elements of the array \n        for (int j = 0; j &lt; size; ++j) { \n            ptr&#91;j] = j + 1; \n        } \n  \n        \/\/ Print the elements of the array \n        printf(\"The elements of the array are: \"); \n        for (int k = 0; k &lt; size; ++k) { \n            printf(\"%d, \", ptr&#91;k]); \n        } \n    } \n  \n    return 0; \n}<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Enter size of elements:6\nMemory successfully allocated using malloc.\nThe elements of the array are: 1, 2, 3, 4, 5, 6, <\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3-dynamically-resizing-array-using-realloc-function\">3. Dynamically Resizing Array Using realloc() Function<\/h2>\n\n\n\n<p>In C, the realloc function is used to change the size of previously allocated memory. It&#8217;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.<\/p>\n\n\n\n<p>Syntax:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ptr = realloc(ptr, newSize);\n<\/code><\/pre>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/ C program to resize dynamic array using realloc() \n\/\/ function \n  \n#include &lt;stdio.h&gt; \n#include &lt;stdlib.h&gt; \n  \nint main() \n{ \n  \n    \/\/ address of the block created hold by this pointer \n    int* ptr; \n    int size = 5; \n  \n  \n    \/\/  Memory allocates dynamically using calloc() \n    ptr = (int*)calloc(size, sizeof(int)); \n  \n    if (ptr == NULL) { \n        printf(\"Memory not allocated.\\n\"); \n        exit(0); \n    } \n    else { \n        printf(\"Memory successfully allocated using \"\n               \"calloc.\\n\"); \n    } \n  \n    \/\/ inserting elements \n    for (int j = 0; j &lt; size; ++j) { \n        ptr&#91;j] = j + 1; \n    } \n  \n    printf(\"The elements of the array are: \"); \n    for (int k = 0; k &lt; size; ++k) { \n        printf(\"%d, \", ptr&#91;k]); \n    } \n  \n    printf(\"\\n\"); \n  \n    size = 10; \n  \n    int *temp = ptr; \n  \n    \/\/  using realloc \n    ptr = realloc(ptr, size * sizeof(int)); \n    if (!ptr) { \n        printf(\"Memory Re-allocation failed.\"); \n        ptr = temp; \n    } \n    else { \n        printf(\"Memory successfully re-allocated using \"\n               \"realloc.\\n\"); \n    } \n  \n    \/\/ inserting new elements \n    for (int j = 5; j &lt; size; ++j) { \n        ptr&#91;j] = j + 10; \n    } \n  \n    printf(\"The new elements of the array are: \"); \n    for (int k = 0; k &lt; size; ++k) { \n        printf(\"%d, \", ptr&#91;k]); \n    } \n    return 0; \n}<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Memory successfully allocated using calloc.\nThe elements of the array are: 1, 2, 3, 4, 5, \nMemory successfully re-allocated using realloc.\nThe new elements of the array are: 1, 2, 3, 4, 5, 15, 16, 17, 18, 19, <\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"4-variable-length-arrays-vl-as\"><strong>4. Variable Length Arrays(VLAs)<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Dynamic Sizing<\/strong>: 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.<\/li>\n\n\n\n<li><strong>Stack Memory Allocation<\/strong>: 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.<\/li>\n\n\n\n<li><strong>Immutable Size<\/strong>: Once you define a VLA with a specific size, you cannot change that size during its lifetime. The size remains fixed.<\/li>\n\n\n\n<li><strong>Limitations<\/strong>: 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.<\/li>\n<\/ul>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\n\/\/ C program to demonstrate the use of VLAs \n#include &lt;stdio.h&gt; \n  \nint main() \n{ \n  \n    int n; \n    printf(\"Enter the size of the array: \"); \n    scanf(\"%d\", &amp;n); \n    \n    int arr&#91;n]; \n  \n    printf(\"Enter elements: \"); \n  \n    for (int i = 0; i &lt; n; ++i) { \n  \n        scanf(\"%d\", &amp;arr&#91;i]); \n    } \n      \n      printf(\"Elements of VLA of Given Size: \"); \n    for (int i = 0; i &lt; n; ++i) { \n  \n        printf(\"%d \", arr&#91;i]); \n    } \n  \n    return 0; \n}<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Enter the size of the array: 5\nEnter elements: 1 2 3 4 5\nElements of VLA of Given Size: 1 2 3 4 5<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5-flexible-array\">5. Flexible Array<\/h2>\n\n\n\n<p>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.<\/p>\n\n\n\n<p>Refer  the structure given below for example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>struct student\n{\n  int len;\n  int \n};<\/code><\/pre>\n\n\n\n<p>Then, we can use the malloc() function to allocate memory:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>struct student *s = malloc(sizeof(*s) + 5 * sizeof(int));\n<\/code><\/pre>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C program to demonstrate the use of Flexible Array Member \n#include &lt;stdio.h&gt; \n#include &lt;stdlib.h&gt; \n  \n\/\/ defining struct \ntypedef struct { \n    int len; \n    int arr&#91;]; \n} fam; \n  \nint main() \n{ \n    \/\/ creating an array member of size 5 \n    fam* fam1 \n        = (fam*)malloc(sizeof(fam*) + 5 * sizeof(int)); \n  \n    \/\/ creating an array mebmer of size 10 \n    fam* fam2 \n        = (fam*)malloc(sizeof(fam*) + 10 * sizeof(int)); \n      \n    \/\/ inserting elements \n    for (int i = 0; i &lt; 5; i++) { \n        fam1-&gt;arr&#91;i] = i + 1; \n    } \n    for (int i = 0; i &lt; 10; i++) { \n        fam2-&gt;arr&#91;i] = i + 10; \n    } \n  \n    \/\/  printing elements \n    printf(\"Array of Size 5:\\n\"); \n    for (int i = 0; i &lt; 5; i++) { \n        printf(\"%d, \", fam1-&gt;arr&#91;i]); \n    } \n    printf(\"\\n\"); \n  \n    printf(\"Array of size 10:\\n\"); \n    for (int i = 0; i &lt; 10; i++) { \n        printf(\"%d, \", fam2-&gt;arr&#91;i]); \n    } \n    return 0; \n}\n<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Array of Size 5:\n1, 2, 3, 4, 5, \nArray of size 10:\n10, 11, 12, 13, 14, 15, 16, 17, 18, 19,<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"dynamic-allocation-of-two-dimensional-array\">Dynamic Allocation of Two-Dimensional Array<\/h2>\n\n\n\n<p>  Creating  a two-dimensional dynamic array in c. &nbsp;These are the  various  methods inorder to produce a 2D dynamic array.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Using a single pointer and a 1D array with pointer arithmetic<\/strong><\/li>\n\n\n\n<li><strong>Using an array of pointers&nbsp;<\/strong><\/li>\n\n\n\n<li><strong>Using a pointer to a pointer&nbsp;<\/strong><\/li>\n\n\n\n<li><strong>Using a double-pointer and one malloc call&nbsp;<\/strong><\/li>\n\n\n\n<li><strong>Using a pointer to Variable Length Array<\/strong><\/li>\n\n\n\n<li><strong>Using a pointer to the first row of VLA<\/strong><\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"faq-dynamic-array-in-c\">FAQ-  Dynamic Array In C<\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1698743429420\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q1. What is a dynamic array in C?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>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.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1698743436081\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q2.What is the syntax of dynamic array in C?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. printf(&#8220;Enter size of elements:&#8221;); scanf(&#8220;%d&#8221;, &amp;size); \/\/<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1698743440985\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q3. How to use dynamic array in class?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. <br \/>Create a new array of the desired size.<br \/>Copy data from the old array to the new one.<br \/>Delete the old array to avoid memory waste.<br \/>Make sure your pointer points to the new array.<br \/>These steps help you resize a dynamic array efficiently.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n\n\n<h2 class=\"wp-block-heading\"><br><\/h2>\n","protected":false},"excerpt":{"rendered":"<p>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, &#8230; <a title=\"Dynamic Array In C\" class=\"read-more\" href=\"https:\/\/www.skillvertex.com\/blog\/dynamic-array-in-c\/\" aria-label=\"More on Dynamic Array In C\">Read more<\/a><\/p>\n","protected":false},"author":4,"featured_media":5404,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27],"tags":[528],"class_list":["post-3202","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c-programming","tag-dynamic-array-in-c","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-33"],"_links":{"self":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3202","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/comments?post=3202"}],"version-history":[{"count":7,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3202\/revisions"}],"predecessor-version":[{"id":10750,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3202\/revisions\/10750"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media\/5404"}],"wp:attachment":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media?parent=3202"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/categories?post=3202"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/tags?post=3202"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}