C Advanced: Array length

C does not provide a built-in way to get the size of an array. You have to do some work up front.

I want to mention the simplest way to do that, first: saving the length of the array in a variable. Sometimes the simple solution is what works best.

Instead of defining the array like this:

int prices[5] = { 1, 2, 3, 4, 5 };

You use a variable for the size:

const int SIZE = 5;
int prices[SIZE] = { 1, 2, 3, 4, 5 };

So if you need to iterate the array using a loop, for example, you use that SIZE variable:

for (int i = 0; i < SIZE; i++) {
  printf("%u\n", prices[i]);
}

The simplest procedural way to get the value of the length of an array is by using the sizeof operator.

First you need to determine the size of the array. Then you need to divide it by the size of one element. It works because every item in the array has the same type, and as such the same size.

Example:

int prices[5] = { 1, 2, 3, 4, 5 };

int size = sizeof prices / sizeof prices[0];

printf("%u", size); /* 5 */

Instead of:

int size = sizeof prices / sizeof prices[0];

you can also use:

int size = sizeof prices / sizeof *prices;

as the pointer to the string points to the first item in the string.

Lessons in this unit:

0: Introduction
1: Input and output
2: Variable scope
3: Static variables
4: Global variables
5: Type definitions
6: Enumerations
7: Structures
8: Command line parameters
9: Header files
10: The preprocessor
11: NULL values
12: Boolean values
13: Nesting functions
14: Conversion specifiers
15: Using quotes
16: String length
17: Returning strings
18: ▶︎ Array length
19: Looping through arrays
20: Checking character values
21: Printing percentage signs
22: Troubleshooting: Implicit function declarations

Join my AI Workshop!

The Web Development BOOTCAMP cohort starts in February 2026