Skip to content

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.

→ Download my free C Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about clang: