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.
download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.