How to determine the length of an array in C

By

Learn how to determine the length of an array in C, either by storing the size in a variable or by dividing sizeof the array by sizeof one element.

~~~

C does not provide a built-in way to get the size of an array. You have to do some work up front. There are two common approaches: storing the size in a variable, or computing it with the sizeof operator.

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]);
}

Using sizeof

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 in bytes. 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 points to the first item in the array.

Careful with function parameters

Here’s the pitfall that catches everyone. The sizeof trick only works in the scope where the array is defined.

When you pass an array to a function, it decays to a pointer to its first element. Inside the function, sizeof gives you the size of a pointer, not the size of the array:

void printLength(int prices[]) {
  int size = sizeof prices / sizeof prices[0];
  printf("%d\n", size); /* 2, not 5! */
}

int main(void) {
  int prices[5] = { 1, 2, 3, 4, 5 };
  printLength(prices);
}

On a 64-bit system a pointer is 8 bytes, and an int is usually 4, so this prints 2 no matter how many items the array holds. Most compilers warn you when you try this.

The fix is to compute the length where the array is defined, and pass it to the function as a separate parameter:

int total(int prices[], int size) {
  int sum = 0;
  for (int i = 0; i < size; i++) {
    sum += prices[i];
  }
  return sum;
}

Then you call it with total(prices, 5), or better, with the sizeof calculation done in main(), where it still works.

Tagged: C · All topics
~~~

Related posts about clang: