Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
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 my free C Handbook
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More clang tutorials:
- Introduction to the C Programming Language
- C Variables and types
- C Constants
- C Operators
- C Conditionals
- How to work with loops in C
- Introduction to C Arrays
- How to determine the length of an array in C
- Introduction to C Strings
- How to find the length of a string in C
- Introduction to C Pointers
- Looping through an array with C
- Booleans in C
- Introduction to C Functions
- How to use NULL in C
- Basic I/O concepts in C
- Double quotes vs single quotes in C
- How to return a string from a C function
- How to solve the implicitly declaring library function warning in C
- How to check a character value in C
- How to print the percentage character using `printf()` in C
- C conversion specifiers and modifiers
- How to access the command line parameters in C
- Scope of variables in C
- Can you nest functions in C?
- Static variables in C
- C Global Variables
- The typedef keyword in C
- C Enumerated Types
- C Structures
- C Header Files
- The C Preprocessor