How to determine the length of an array in C
How to determine the length of an array in C
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.
→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
→ 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