An array is a variable that can store multiple values
Syntax
Warning
It’s important to note that the size and type of an array cannot be changed once it is declared.
Example:
Access Array Elements
You can access elements of an array by indices.
Few keynotes:
-
Arrays have 0 as the first index
- If arr size =
n
, last element index =n-1
- If arr size =
-
Suppose the starting address of
arr[0]
is 2120d -
The address of the
mark[1]
will be 2124d (+4) -
The address of
mark[2]
will be 2128d (+4)- This is because the size of a
float
is 4 bytes.
- This is because the size of a
Learn about C Memory Address
How to initialize an array?
It is possible to initialize an array during declaration
You can also initialize an array like this
Here, we haven’t specified the size. However, the compiler knows its size is 5 as we are initializing it with 5 elements.
Change Value of Array elements
Input and Output Array Elements
Here’s how you can take input from the user and store it in an array element.
Here’s how you can print an individual element of an array.
Access elements out of its bound!
You can access the array elements from testArray[0]
to testArray[9]
.
Now let’s say if you try to access testArray[12]
. The element is not available. This may cause unexpected output (undefined behavior). Sometimes you might get an error and some other time your program may run correctly.
Hence, you should never access elements of an array outside of its bound.
Loop Through an Array
You can loop through the array elements with the for
loop.
The following example outputs all elements in the myNumbers
array:
Example: