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 method to obtainLarge numbers. You must do some work first.

I want to mention the easiest way: first save the length of the array in a variable. Sometimes, a simple solution is the most effective method.

Instead of defining the array like this:

int prices[5] = { 1, 2, 3, 4, 5 };

You use a variable as the size:

const int SIZE = 5;
int prices[SIZE] = { 1, 2, 3, 4, 5 };

So, for example, if you need to use a loop to iterate the array, you can useSIZEChanging:

for (int i = 0; i < SIZE; i++) {
  printf("%u\n", prices[i]);
}

The easiest way to get the length value of an array is to usesizeofoperator.

First, you need to determine the size of the array. Then you need to divide it by the size of an element. It works because each item in the array has the same type and the same size.

example:

int prices[5] = { 1, 2, 3, 4, 5 };

int size = sizeof prices / sizeof prices[0];

printf("%u", size); /* 5 */

instead:

int size = sizeof prices / sizeof prices[0];

You can also use:

int size = sizeof prices / sizeof *prices;

AspointerPoints to the first item of the string.

Download mine for freeC manual


More clang tutorials: