How to get the Length of an Array in C

There isn’t really a standard way to get the length of array in C. This means you need to do some additional work to achieve getting the length of an array when using C.

Creating and Looping through an Array in C

Usually you would create an array as follows:

int items[5] = {1, 2, 3, 4, 5};
Code language: C++ (cpp)

You could always define the size right off the bat:

const int SIZE = 5; int items[SIZE] = {1, 2, 3, 4, 5};
Code language: C++ (cpp)

This way if you need to loop through the array later on, you can use your SIZE variable.

for (int i=0; i<SIZE; i++) { printf("%u\n", items[i]); }
Code language: C++ (cpp)

Using the sizeof Operator for Array Length in C

C does however provide you with a sizeof operator which allows you to get the size of an element.

To get this to work properly, you will need to first get the size of the array and then divide it by the size of one of the individual elements. This only works if every element is of the exact same type.

This will help you get the length of array.

int items[5] = {1,2,3,4,5}; int size = sizeof items / sizeof items[0]; // 5 printf("%u", size);
Code language: C++ (cpp)

Another way to do it is to do this:

int items[5] = {1,2,3,4,5}; int size = sizeof items / sizeof *items; // 5 printf("%u", size);
Code language: C++ (cpp)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments