

{"id":120652,"date":"2023-11-22T18:00:15","date_gmt":"2023-11-22T12:30:15","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=120652"},"modified":"2023-11-22T18:12:43","modified_gmt":"2023-11-22T12:42:43","slug":"arrays-in-c-programming","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/","title":{"rendered":"Arrays in C Programming"},"content":{"rendered":"<p>One of the most fundamental and popular data structures in C programming is arrays. An array is a group of identical data-typed objects kept together in memory. Programmers can conveniently store and access numerous values using an array by using a single identifier.<\/p>\n<p>This tutorial will teach us how to declare, initialise, and use arrays in C. We will discuss single- and multi-dimensional arrays as well as sorting, inserting, and deleting data from an array. The main ideas are illustrated using examples. By the conclusion, you will have a firm understanding of arrays in C, laying the groundwork for resolving a variety of practical issues.<\/p>\n<h2>Understanding Arrays in C<\/h2>\n<p>A collection of identically typed elements is kept in an array, which is a form of data structure. For example, an array can store a list of integers, characters, floating point values, or any other data type.<\/p>\n<p>The memory used to store an array&#8217;s elements is contiguous, which means that each element is kept next to the other. The elements can be accessed using an index value that represents the position of that element in the array.<\/p>\n<p><strong>For example, consider the following array declaration:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int numbers[5];<\/pre>\n<p>This declares an array named numbers capable of storing 5 integer values. The elements can be accessed as numbers[0], numbers[1], numbers[2] and so on.<\/p>\n<p>Arrays enable easy access and manipulation of data sets. The key benefit is that we can represent many related values using a single identifier variable instead of having to use separate variables for each value.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/array-elements.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-120741 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/array-elements.webp\" alt=\"array elements\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/array-in-c.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-120742 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/array-in-c.webp\" alt=\"array in c\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<h3>Properties of Array in C<\/h3>\n<ul>\n<li>All array elements share the same data type and occupy a uniform size, such as 4 bytes for integers (e.g., int).<\/li>\n<li>Array elements are stored consecutively in memory, starting from the lowest memory address.<\/li>\n<li>Random access to array elements is possible because their addresses can be calculated using the base address and the size of the data type.<\/li>\n<\/ul>\n<h3>Advantages of Arrays in C<\/h3>\n<ul>\n<li><strong>Efficient Data Structure:<\/strong> Arrays provide efficient storage and access to elements of the same data type.<\/li>\n<li><strong>Random Access:<\/strong> Elements can be directly accessed using their index, allowing for quick retrieval and modification.<\/li>\n<li><strong>Memory Efficiency:<\/strong> Arrays allocate memory in a contiguous block, reducing memory overhead.<\/li>\n<li><strong>Predictable Memory Allocation:<\/strong> Memory for arrays is allocated at compile-time, making memory management more predictable.<\/li>\n<li><strong>Simplicity:<\/strong> Arrays are simple and easy to use for managing collections of data.<\/li>\n<\/ul>\n<h3>Disadvantages of Arrays in C<\/h3>\n<ul>\n<li><strong>Fixed Size:<\/strong> Arrays have a fixed size, making it challenging to handle dynamic data or accommodate varying data sizes.<\/li>\n<li><strong>Inefficient Insertions\/Deletions:<\/strong> Adding or removing elements within an array can be inefficient as it may require shifting elements.<\/li>\n<li><strong>Wasted Memory:<\/strong> If an array is allocated a large size but doesn&#8217;t utilize all of it, memory can be wasted.<\/li>\n<li><strong>Limited Flexibility:<\/strong> Arrays are not inherently dynamic; managing variable-sized data requires extra effort.<\/li>\n<li><strong>No Built-in Bounds Checking:<\/strong> C arrays lack built-in safeguards against buffer overflows, which can lead to memory corruption.<\/li>\n<\/ul>\n<h3>Declaring and Initializing Arrays<\/h3>\n<p>To declare an array in C, we specify the data type of elements followed by the array name and size enclosed in square brackets [].<\/p>\n<p><strong>For example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">double prices[10]; \/\/ array of 10 doubles\r\nchar letters[26]; \/\/ array of 26 chars<\/pre>\n<p>A positive integer constant greater than zero must define the array size. It represents the most elements an array can contain.<\/p>\n<p>When an array is declared, it can be initialised by providing a list of values separated by commas and encased in curly brackets.<\/p>\n<p><strong>For instance:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int n[] = {56,23,79,82,12,43,76}; \/\/ n contains 7 elements \r\nchar vowels[] = {'a', 'e', 'i', 'o', 'u'};<\/pre>\n<p>If no size is specified, the size is inferred from the number of initialization values.<\/p>\n<p><strong>Some rules for array declaration:<\/strong><\/p>\n<ul>\n<li>Array name can be any valid identifier.<\/li>\n<li>The index of an array ranges from 0 to size-1.<\/li>\n<li>Elements are stored contiguously in memory.<\/li>\n<li>Array size must be an integer constant greater than 0.<\/li>\n<li>Garbage values can be found in uninitialized arrays.<\/li>\n<\/ul>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/array-intialization-and-decleration.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-120743 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/array-intialization-and-decleration.webp\" alt=\"array intialization and decleration\" width=\"600\" height=\"800\" \/><\/a><\/p>\n<h3><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/array-in-c-mark.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-120792 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/array-in-c-mark.webp\" alt=\"array in c mark\" width=\"600\" height=\"338\" \/><\/a><\/h3>\n<h3>Accessing Array Elements<\/h3>\n<p>The index notation can be used to retrieve specific array elements. Following the array name are square brackets [] that specify the index.<\/p>\n<p><strong>For example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int nums[5] = {1, 2, 3, 4, 5}; \r\n\r\nint first = nums[0]; \/\/ access first element\r\nint second = nums[1]; \/\/ access second element\r\n\r\nnums[3] = 10; \/\/ modify fourth element<\/pre>\n<p>In C, undefined behaviour results from trying to access an index that is outside the array&#8217;s boundaries (negative index or &gt;= size).<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/access-array-elements.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-120744 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/access-array-elements.webp\" alt=\"access array elements\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<h3>Types of Arrays in C<\/h3>\n<h4>Single Dimensional Arrays<\/h4>\n<p>Single dimensional or 1D arrays are the simplest form of arrays. 1D arrays store elements sequentially (one after another in memory).<\/p>\n<p><strong>Examples:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">float temp[10]; \/\/ 1D array of 10 floats\r\n\r\nchar name[] = \"John\"; \/\/ 1D array of characters  \r\n\r\nint nums[] = {1, 2, 3}; \/\/ 1D array initialization<\/pre>\n<h4>Multidimensional Arrays<\/h4>\n<p>C allows declaring arrays of two or more dimensions. Such arrays are known as multidimensional arrays.<\/p>\n<p>A 2D array, also known as a matrix, can be pictured as a table with rows and columns, for instance.<\/p>\n<p>A 2D array arr[R][C] has R rows and C columns, with R * C elements.<\/p>\n<p>Elements are stored row-wise in memory. <strong>For example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int mat[3][3]; \/\/ 3 x 3 2D array \r\n\r\nmat[0][0] mat[0][1] mat[0][2]\r\nmat[1][0] mat[1][1] mat[1][2] \r\nmat[2][0] mat[2][1] mat[2][2]<\/pre>\n<p>Arrays with more than 2 dimensions are possible in C but rarely used in practice.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/type-of-array.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-120745 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/type-of-array.webp\" alt=\"type of array\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<h3>Why Do We Need Arrays?<\/h3>\n<p>Arrays enable managing related data efficiently. For example, storing 50 integers separately would require 50 variable names and a lot of code. Arrays let us use a single identifier data[50].<\/p>\n<h4>Key reasons to use arrays:<\/h4>\n<ul>\n<li>Arrays allow access to elements efficiently using index notation.<\/li>\n<li>Code using arrays is concise and readable since related data is together.<\/li>\n<li>Memory usage is efficient as arrays store elements contiguously.<\/li>\n<li>Operations like search, sort, insert and delete can be easily performed on arrays.<\/li>\n<\/ul>\n<h4>Common array use cases:<\/h4>\n<ul>\n<li>Storing and managing large data sets like student records or product info.<\/li>\n<li>Representing real world collections like days of the week.<\/li>\n<li>Look-up tables, matrices, hash-tables.<\/li>\n<li>Used by algorithms like sorting, searching, and graph traversals.<\/li>\n<\/ul>\n<h3>Input and Output of C Arrays<\/h3>\n<h4>Input<\/h4>\n<p>We can read values into an array using a loop. Typically for loop is used to iterate over the array indexes.<\/p>\n<p><strong>Example code to read 10 numbers from user into an array:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int nums[10];\r\n\r\nfor (int i = 0; i &lt; 10; i++) {\r\n  printf(\"Enter number: \");\r\n  scanf(\"%d\", &amp;nums[i]); \r\n}<\/pre>\n<p><strong>Output<\/strong><\/p>\n<p><strong>To print array elements, again for loop can be used:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">for (int i = 0; i &lt; 10; i++) {\r\n  printf(\"%d \", nums[i]); \r\n}<\/pre>\n<p><strong>Output all elements in a formatted manner:<\/strong><\/p>\n<p><strong>Index Value<\/strong><br \/>\n0 2<br \/>\n1 4<br \/>\n2 7<br \/>\n3 5<\/p>\n<h3>Advantages and Disadvantages of Arrays in C<\/h3>\n<h4>Advantages<\/h4>\n<ul>\n<li>Contiguous memory allocation improves cache performance.<\/li>\n<li>Memory access using an index is faster than pointer dereferencing.<\/li>\n<li>Code is concise using index notation compared to separate variables.<\/li>\n<li>Useful built-in support for common data structures like stacks.<\/li>\n<li>Efficient implementations of algorithms like search and sort.<\/li>\n<\/ul>\n<h4>Disadvantages<\/h4>\n<ul>\n<li>Fixed-size at declaration limits flexibility. The data size cannot change dynamically.<\/li>\n<li>Memory wastage if an array is declared very large but not fully used.<\/li>\n<li>It cannot grow or shrink in size at runtime like linked data structures.<\/li>\n<li>Insertion and deletion costs are high due to the shifting of elements.<\/li>\n<\/ul>\n<p>So, arrays are best suited for relatively static data sets and provide very efficient access. For dynamic data, it is better to use pointers and dynamic memory allocation.<\/p>\n<h3>Examples<\/h3>\n<h4>Insertion and Deletion<\/h4>\n<p><strong>To insert an element at index pos:<\/strong><\/p>\n<ul>\n<li>Increase array size by 1 (or reallocate memory for larger size)<\/li>\n<li>Move elements from pos onwards one step back<\/li>\n<\/ul>\n<p><strong>To delete an element at index pos:<\/strong><\/p>\n<ul>\n<li>Move elements from pos+1 onwards one step forward<\/li>\n<li>Decrease array size by 1<\/li>\n<\/ul>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;stdio.h&gt;\r\n\r\n#define SIZE 5\r\n\r\nvoid printArray(int arr[], int n) {\r\n  for(int i=0; i&lt;n; i++) {\r\n    printf(\"%d \", arr[i]);\r\n  }\r\n  printf(\"\\n\");\r\n}\r\n\r\n\/\/ Function to insert an element\r\nvoid insert(int arr[], int size, int element, int pos) {\r\n\r\n  int newArr[size+1];\r\n  \r\n  \/\/ Insert the element\r\n  for(int i=0; i&lt;size+1; i++) {\r\n    if(i &lt; pos) {\r\n      newArr[i] = arr[i]; \r\n    }\r\n    else if(i == pos) {\r\n      newArr[i] = element;\r\n    }\r\n    else {\r\n      newArr[i] = arr[i-1]; \r\n    }\r\n  }\r\n\r\n  \/\/ Copy back new array into original array\r\n  for(int i=0; i&lt;size+1; i++) {\r\n    arr[i] = newArr[i]; \r\n  }\r\n}\r\n\r\n\/\/ Function to delete an element\r\nvoid delete(int arr[], int size, int pos) {\r\n  \r\n  for(int i=pos; i&lt;size-1; i++) {\r\n    arr[i] = arr[i+1];\r\n  }\r\n\r\n}\r\n\r\nint main() {\r\n\r\n  int arr[SIZE] = {1, 2, 3, 4, 5};\r\n  \r\n  printf(\"Original Array: \");\r\n  printArray(arr, SIZE);  \r\n\r\n  int element = 10, pos = 2;\r\n\r\n  \/\/ Insert 10 at index 2\r\n  insert(arr, SIZE, element, pos);\r\n\r\n  printf(\"After Insertion: \");\r\n  printArray(arr, SIZE+1);\r\n\r\n  \/\/ Delete element at index 2\r\n  int del_pos = 2;\r\n  delete(arr, SIZE+1, del_pos);\r\n\r\n  printf(\"After Deletion: \");\r\n  printArray(arr, SIZE);\r\n\r\n  return 0;\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Original Array:<\/strong><br \/>\n1 2 3 4 5<\/p>\n<p><strong>After Insertion:<\/strong><br \/>\n1 2 10 3 4 5<\/p>\n<p><strong>After Deletion:<\/strong><br \/>\n1 2 4 5<\/p>\n<h3>Array Declaration, Input and Output<\/h3>\n<p>This C program initializes an array with a size of 5. It then prompts the user to input five numbers one by one. After input, it displays the entered numbers in a list format, demonstrating basic input and output operations with arrays.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;stdio.h&gt;\r\n\r\n#define SIZE 5\r\n\r\nint main() {\r\n  int nums[SIZE];\r\n  \r\n  \/\/ Array input\r\n  for (int i = 0; i &lt; SIZE; i++) {\r\n    printf(\"Enter number: \");\r\n    scanf(\"%d\", &amp;nums[i]);\r\n  }  \r\n\r\n  \/\/ Array output \r\n  printf(\"Array elements: \");\r\n  for (int i = 0; i &lt; SIZE; i++) {\r\n    printf(\"%d \", nums[i]); \r\n  }\r\n\r\n  return 0;\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Enter number:<\/strong> 10<br \/>\n<strong>Enter number:<\/strong> 20<br \/>\n<strong>Enter number:<\/strong> 30<br \/>\n<strong>Enter number:<\/strong> 40<br \/>\n<strong>Enter number:<\/strong> 50<br \/>\n<strong>Array elements:<\/strong> 10 20 30 40 50<\/p>\n<h3>Sorting Array Elements in C<\/h3>\n<p>There are many sorting algorithms like bubble, selection and insertion sort that can be used to sort arrays in C.<\/p>\n<p><strong>The following implements a simple bubble sort on an array:<\/strong><\/p>\n<p>This C program demonstrates the Bubble Sort algorithm to sort an array of integers. It initializes an array, displays the original array, sorts it using the Bubble Sort function, and then displays the sorted array. Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order until the entire array is sorted.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;stdio.h&gt;\r\n\r\n\/\/ Function to perform Bubble Sort\r\nvoid bubbleSort(int arr[], int n) {\r\n  int temp;\r\n  for (int i = 0; i &lt; n - 1; i++) {\r\n    for (int j = 0; j &lt; n - i - 1; j++) {\r\n      if (arr[j] &gt; arr[j + 1]) {\r\n        \/\/ Swap elements\r\n        temp = arr[j];\r\n        arr[j] = arr[j + 1];\r\n        arr[j + 1] = temp;\r\n      }\r\n    }\r\n  }\r\n}\r\n\r\nint main() {\r\n  int arr[] = {64, 34, 25, 12, 22, 11, 90};\r\n  int n = sizeof(arr) \/ sizeof(arr[0]);\r\n\r\n  printf(\"Original array: \");\r\n  for (int i = 0; i &lt; n; i++) {\r\n    printf(\"%d \", arr[i]);\r\n  }\r\n\r\n  \/\/ Call the bubbleSort function to sort the array\r\n  bubbleSort(arr, n);\r\n\r\n  printf(\"\\nSorted array: \");\r\n  for (int i = 0; i &lt; n; i++) {\r\n    printf(\"%d \", arr[i]);\r\n  }\r\n\r\n  return 0;\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Original array:<\/strong> 64 34 25 12 22 11 90<br \/>\n<strong>Sorted array:<\/strong> 11 12 22 25 34 64 90<\/p>\n<h3>Finding Largest and Smallest in Array<\/h3>\n<p><strong>To find the minimum and maximum elements in a 1D array:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;stdio.h&gt;\r\n\r\nint main() {\r\n  int arr[] = {64, 34, 25, 12, 22, 11, 90};\r\n  int n = sizeof(arr) \/ sizeof(arr[0]);\r\n\r\n  int smallest = arr[0];\r\n  int largest = arr[0];\r\n\r\n  for (int i = 1; i &lt; n; i++) {\r\n    if (arr[i] &lt; smallest) {\r\n      smallest = arr[i];\r\n    }\r\n\r\n    if (arr[i] &gt; largest) {\r\n      largest = arr[i];\r\n    }\r\n  }\r\n\r\n  printf(\"Largest = %d, Smallest = %d\", largest, smallest);\r\n\r\n  return 0;\r\n}<\/pre>\n<p>This C program finds and prints the largest and smallest numbers in an integer array. It initializes two variables, smallest and largest, with the first array element and then iterates through the array to update these values based on the array elements. Finally, it prints the found largest and smallest numbers.<\/p>\n<p><strong>Output:<\/strong><\/p>\n<p>Largest = 90, Smallest = 11<\/p>\n<h3>Working with 2D Arrays in C<\/h3>\n<p><strong>2D arrays are commonly used to represent matrices:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;stdio.h&gt;\r\n\r\nint main() {\r\n  int mat[3][3];\r\n  int i, j;\r\n\r\n  \/\/ Initialize the 2D array\r\n  mat[0][0] = 1;\r\n  mat[0][1] = 2;\r\n  mat[0][2] = 3;\r\n  mat[1][0] = 4;\r\n  mat[1][1] = 5;\r\n  mat[1][2] = 6;\r\n  mat[2][0] = 7;\r\n  mat[2][1] = 8;\r\n  mat[2][2] = 9;\r\n\r\n  \/\/ Input values into the 2D array\r\n  printf(\"Enter elements of the 3x3 matrix:\\n\");\r\n  for (i = 0; i &lt; 3; i++) {\r\n    for (j = 0; j &lt; 3; j++) {\r\n      scanf(\"%d\", &amp;mat[i][j]);\r\n    }\r\n  }\r\n\r\n  \/\/ Output the 2D array\r\n  printf(\"Matrix elements:\\n\");\r\n  for (i = 0; i &lt; 3; i++) {\r\n    for (j = 0; j &lt; 3; j++) {\r\n      printf(\"%d \", mat[i][j]);\r\n    }\r\n    printf(\"\\n\");\r\n  }\r\n\r\n  return 0;\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Enter elements of the 3&#215;3 matrix:<\/strong><br \/>\n1 2 3<br \/>\n4 5 6<br \/>\n7 8 9<br \/>\n<strong>Matrix elements:<\/strong><br \/>\n1 2 3<br \/>\n4 5 6<br \/>\n7 8 9<\/p>\n<h3>C Array Operations<\/h3>\n<p><strong>Some common operations performed on arrays:<\/strong><\/p>\n<ul>\n<li><strong>Traversal &#8211;<\/strong> Access each element sequentially using looping.<\/li>\n<li><strong>Insertion &#8211;<\/strong> Add a new element at a specific index.<\/li>\n<li><strong>Deletion &#8211;<\/strong> Remove element from specific index.<\/li>\n<li><strong>Searching &#8211;<\/strong> Find specific elements in an array using linear or binary search.<\/li>\n<li><strong>Sorting &#8211;<\/strong> Sort elements in a specific order using algorithms.<\/li>\n<li><strong>Reversal &#8211;<\/strong> Reverse order of elements in place.<\/li>\n<\/ul>\n<p>These operations are implemented using loops combined with conditional statements and variable assignments.<\/p>\n<p><strong>For example, to search an element key in an array arr[]:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">for (i = 0; i &lt; size; i++) {\r\n  if (arr[i] == key) {\r\n    \/\/ found, break out of loop\r\n    break;\r\n  }\r\n}<\/pre>\n<p>Built-in functions like memcpy() can also be used for bulk operations like copying entire arrays.<\/p>\n<h3>Array Size and Memory<\/h3>\n<h4>Sizeof Operator<\/h4>\n<p><strong>We can find the total size (in bytes) allocated for an array using the sizeof operator:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int arr[100];\r\nsize_t size = sizeof(arr); \/\/ size = 100 * sizeof(int)<\/pre>\n<p>For 2D array arr[R][C], sizeof(arr) gives total size = R * C * sizeof(datatype).<\/p>\n<h3>Memory Allocation in C<\/h3>\n<p>Arrays are stored in continuous memory locations. The collection of all memory cells used to store array elements is called the array memory allocation.<\/p>\n<p>Large arrays can cause stack overflow if declared globally or in functions<strong>. Dynamic memory allocation using malloc() is preferred for large arrays:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int *arr = (int *)malloc(100 * sizeof(int)); \/\/ allocates 400 bytes<\/pre>\n<p>The array size should be chosen carefully to avoid memory wastage. Accessing out of bounds array indexes can corrupt other variables and crash programs.<\/p>\n<h3>Arrays vs Pointers in C<\/h3>\n<p>In C, arrays often decay into pointers. For example, when an array is passed to a function, it decays into a pointer to its first element.<\/p>\n<p><strong>The major differences between arrays and pointers are:<\/strong><\/p>\n<ul>\n<li>Arrays are fixed sized declared storage. Pointers are just addresses without storage.<\/li>\n<li>Array elements are accessed using []. Pointer elements are accessed using * dereference operator.<\/li>\n<li>Sizeof array provides the total allocated storage. Sizeof pointer just gives size of address.<\/li>\n<li>Arrays can be initialized; pointers need to be explicitly allocated.<\/li>\n<li>Multidimensional arrays are supported, but not pointers.<\/li>\n<\/ul>\n<p><strong>Pointers and arrays are often used together in functions to modify arrays passed as arguments.<\/strong><\/p>\n<table>\n<tbody>\n<tr>\n<td><b>Pointer<\/b><\/td>\n<td><b>Array<\/b><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">A pointer is a derived data type that can store the memory address of other variables.<\/span><\/td>\n<td><span style=\"font-weight: 400\">An array is a homogeneous collection of data items of the same type, such as int, char, etc.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">Pointers need to be allocated memory at runtime, usually using malloc() or calloc().<\/span><\/td>\n<td><span style=\"font-weight: 400\">Arrays are allocated memory at compile time based on the declared size.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">A pointer is a single variable that stores one memory address.<\/span><\/td>\n<td><span style=\"font-weight: 400\">An array is a contiguous collection of multiple variables of the same type.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">Pointers are dynamic and flexible &#8211; the memory can be freed and reallocated during execution.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Arrays are static and fixed in size once declared. The size cannot be changed during runtime.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">Pointer arithmetic can be used to traverse data.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Array elements are accessed using index notation [] for fast access.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">Dereferencing operator * is used to access the value at a pointer address.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Array elements are accessed directly using the index.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">The sizeof operator on pointers returns the size of the pointer variable.<\/span><\/td>\n<td><span style=\"font-weight: 400\">The sizeof operator on arrays returns the total allocated size.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">Multidimensional pointers are not supported in C.<\/span><\/td>\n<td><span style=\"font-weight: 400\">C supports multidimensional arrays.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">Pointers reduce code and improve performance in some cases.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Arrays allow easier access and operations on data sets.<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Multidimensional Arrays in C<\/h3>\n<p>C supports multidimensional arrays of two or more dimensions. 2D arrays are commonly used to represent matrices and grids.<\/p>\n<p><strong>For example, a 2D array:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int mat[3][3]; \/\/ 3 x 3 array \r\n\r\n\/\/ access element at row 2, column 1\r\nint num = mat[2][1];<\/pre>\n<p>Elements are stored row-wise in memory. A 2D array is actually an array of arrays.<\/p>\n<p><strong>Initialization:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int mat[3][3] = {\r\n  {1, 2, 3}, \r\n  {4, 5, 6},\r\n  {7, 8, 9}\r\n};<\/pre>\n<p>We can declare arrays of more than 2 dimensions in a similar fashion.<\/p>\n<p>Operations like traversal, search, sort, etc can be performed on multidimensional arrays by using nested loops for each dimension.<\/p>\n<h3>C Arrays in Functions<\/h3>\n<p>Arrays can be passed to functions in both C and C++. Since arrays decay into pointers, the array is not passed by value but rather by reference.<\/p>\n<p>Any modifications to the array elements in the function will be reflected in the caller.<\/p>\n<p><strong>For example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;stdio.h&gt;\r\n\r\n\/\/ Function to double array elements\r\nvoid doubleElements(int arr[], int n) {\r\n  for (int i = 0; i &lt; n; i++) {\r\n    arr[i] *= 2; \/\/ Doubles the existing element\r\n  }\r\n}\r\n\r\nint main() {\r\n  int nums[] = {1, 2, 3, 4};\r\n  int n = sizeof(nums) \/ sizeof(nums[0]);\r\n\r\n  \/\/ Call the doubleElements function to double the elements of the array\r\n  doubleElements(nums, n);\r\n\r\n  \/\/ Display the modified array\r\n  printf(\"Modified array: \");\r\n  for (int i = 0; i &lt; n; i++) {\r\n    printf(\"%d \", nums[i]);\r\n  }\r\n  printf(\"\\n\");\r\n\r\n  return 0;\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Modified array:<\/strong> 2 4 6 8<\/p>\n<p>We can prevent modification by passing as const. Bound checking is essential for array parameters.<\/p>\n<p>Multi-dimensional arrays are passed similarly by decaying into a pointer to an array of pointers.<\/p>\n<h3>Conclusion<\/h3>\n<p>Arrays allow us to represent real world collections of data efficiently in programs. Understanding how to declare, initialize, access, modify and operate on arrays is essential knowledge for any C programmer.<\/p>\n<p>This article covered the array basics from single-dimensional to multidimensional arrays in C. We explored the array of properties, advantages, limitations and popular use cases. Examples were provided for common array operations like insertion, deletion, traversal, search, sort, etc.<\/p>\n<p>With this array foundation, you can now apply arrays to write better C programs and algorithms for real-world problems. Remember to use arrays where fixed contiguous data storage makes sense and pointers or dynamic data structures where more flexibility is needed.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>One of the most fundamental and popular data structures in C programming is arrays. An array is a group of identical data-typed objects kept together in memory. Programmers can conveniently store and access numerous&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":120655,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[19488],"tags":[23926,28384,23914,28585],"class_list":["post-120652","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c-programming","tag-arrays-in-c","tag-arrays-in-c-programming","tag-c-programming","tag-c-tutorial"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Arrays in C Programming - DataFlair<\/title>\n<meta name=\"description\" content=\"This tutorial will teach us how to declare, initialise, and use arrays in C. We will discuss single- and multi-dimensional arrays.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Arrays in C Programming - DataFlair\" \/>\n<meta property=\"og:description\" content=\"This tutorial will teach us how to declare, initialise, and use arrays in C. We will discuss single- and multi-dimensional arrays.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-11-22T12:30:15+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-11-22T12:42:43+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/arrays-in-c.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"12 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Arrays in C Programming - DataFlair","description":"This tutorial will teach us how to declare, initialise, and use arrays in C. We will discuss single- and multi-dimensional arrays.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/","og_locale":"en_US","og_type":"article","og_title":"Arrays in C Programming - DataFlair","og_description":"This tutorial will teach us how to declare, initialise, and use arrays in C. We will discuss single- and multi-dimensional arrays.","og_url":"https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-11-22T12:30:15+00:00","article_modified_time":"2023-11-22T12:42:43+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/arrays-in-c.webp","type":"image\/webp"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"12 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"Arrays in C Programming","datePublished":"2023-11-22T12:30:15+00:00","dateModified":"2023-11-22T12:42:43+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/"},"wordCount":2190,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/arrays-in-c.webp","keywords":["arrays in C","arrays in c programming","c programming","c tutorial"],"articleSection":["C Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/","url":"https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/","name":"Arrays in C Programming - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/arrays-in-c.webp","datePublished":"2023-11-22T12:30:15+00:00","dateModified":"2023-11-22T12:42:43+00:00","description":"This tutorial will teach us how to declare, initialise, and use arrays in C. We will discuss single- and multi-dimensional arrays.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/arrays-in-c.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/arrays-in-c.webp","width":1200,"height":628,"caption":"arrays in c"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/arrays-in-c-programming\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"C Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/c-programming\/"},{"@type":"ListItem","position":3,"name":"Arrays in C Programming"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/120652","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=120652"}],"version-history":[{"count":6,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/120652\/revisions"}],"predecessor-version":[{"id":126653,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/120652\/revisions\/126653"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/120655"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=120652"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=120652"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=120652"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}