In C, an array is a collection of elements of the same data type that are stored in contiguous memory locations. It allows you to store multiple values of the same type under a single variable name. Arrays provide a convenient way to work with groups of related data.
Here’s the general syntax for declaring an array in C:
datatype arrayName[arraySize];
The datatype represents the data type of the elements in the array, such as int, float, char, etc. The arrayName is the name given to the array, and arraySize specifies the number of elements the array can hold.
For example, here’s how you can declare an array of integers with 5 elements:
<span class="hljs-type">int</span> numbers[<span class="hljs-number">5</span>];
This creates an integer array named numbers that can hold 5 integer values. The elements in the array are numbered from 0 to 4, which means you can access each element using its index.
You can also initialize an array at the time of declaration by providing a comma-separated list of values enclosed in curly braces {}:
<span class="hljs-type">int</span> numbers[<span class="hljs-number">5</span>] = {<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>, <span class="hljs-number">50</span>};
This initializes the numbers array with the values 10, 20, 30, 40, and 50.
To access or modify individual elements of an array, you use the array name followed by the index of the element within square brackets:
numbers[<span class="hljs-number">0</span>] = <span class="hljs-number">15</span>; <span class="hljs-comment">// Assigns the value 15 to the first element</span>
<span class="hljs-type">int</span> x = numbers[<span class="hljs-number">2</span>]; <span class="hljs-comment">// Retrieves the value of the third element</span>
Note that array indices in C start from 0. So, numbers[0] refers to the first element, numbers[1] refers to the second element, and so on.
Arrays in C are fixed in size, meaning the number of elements specified during declaration cannot be changed later. If you need a dynamically resizable collection, you may consider using other data structures or dynamic memory allocation techniques like malloc and realloc.
