← flaviocopes.com

How to determine the length of an array in C

Published Feb 06 2020

Psssst! The 2023 WEB DEVELOPMENT BOOTCAMP is starting on FEBRUARY 01, 2023! SIGNUPS ARE NOW OPEN to this 10-weeks cohort course. Learn the fundamentals, HTML, CSS, JS, Tailwind, React, Next.js and much more! ✨

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.


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 write books for developers 👇🏼

© 2023 Flavio Copes Flavio Copes made in Italy 🇮🇹 using Notion to Site Notion to Site