Skip to content

How to determine the length of an array in C

New Course Coming Soon:

Get Really Good at Git

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.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my C Handbook

Here is how can I help you: