Introduction to C Arrays
An introduction to C Arrays
An array is a variable that stores multiple values.
Every value in the array, in C, must have the same type. This means you will have arrays of int
values, arrays of double
values, and more.
You can define an array of int
values like this:
int prices[5];
You must always specify the size of the array. C does not provide dynamic arrays out of the box (you have to use a data structure like a linked list for that).
You can use a constant to define the size:
const int SIZE = 5;
int prices[SIZE];
You can initialize an array at definition time, like this:
int prices[5] = { 1, 2, 3, 4, 5 };
But you can also assign a value after the definition, in this way:
int prices[5];
prices[0] = 1;
prices[1] = 2;
prices[2] = 3;
prices[3] = 4;
prices[4] = 5;
Or, more practical, using a loop:
int prices[5];
for (int i = 0; i < 5; i++) {
prices[i] = i + 1;
}
And you can reference an item in the array by using square brackets after the array variable name, adding an integer to determine the index value. Like this:
prices[0]; /* array item value: 1 */
prices[1]; /* array item value: 2 */
Array indexes start from 0, so an array with 5 items, like the prices
array above, will have items ranging from prices[0]
to prices[4]
.
The interesting thing about C arrays is that the variable name of the array, prices
in the above example, is a pointer to the first element of the array, and as such can be used like a normal pointer.
Another interesting thing is this: all elements of an array are stored sequentially in memory, one right after another, so you can access any item using pointer math. Not something that normally happens with higher-level programming languages.
→ I wrote 17 books to help you become a better developer:
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025