Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard function in C that would return the length of an array?

Tags:

arrays

c

Is there a standard function in C that would return the length of an array?

like image 566
user133466 Avatar asked Oct 21 '09 04:10

user133466


People also ask

Can you get the length of an array in C?

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.

What function returns the length of an array?

length. The length property of an object which is an instance of type Array sets or returns the number of elements in that array.

How do you get array size in C?

We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);

Which function is used to return the length the number of elements of an array?

size() function is used to return the size of the list container or the number of elements in the list container.


1 Answers

Often the technique described in other answers is encapsulated in a macro to make it easier on the eyes. Something like:

#define COUNT_OF( arr) (sizeof(arr)/sizeof(0[arr])) 

Note that the macro above uses a small trick of putting the array name in the index operator ('[]') instead of the 0 - this is done in case the macro is mistakenly used in C++ code with an item that overloads operator[](). The compiler will complain instead of giving a bad result.

However, also note that if you happen to pass a pointer instead of an array, the macro will silently give a bad result - this is one of the major problems with using this technique.

I have recently started to use a more complex version that I stole from Google Chromium's codebase:

#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x]))))) 

In this version if a pointer is mistakenly passed as the argument, the compiler will complain in some cases - specifically if the pointer's size isn't evenly divisible by the size of the object the pointer points to. In that situation a divide-by-zero will cause the compiler to error out. Actually at least one compiler I've used gives a warning instead of an error - I'm not sure what it generates for the expression that has a divide by zero in it.

That macro doesn't close the door on using it erroneously, but it comes as close as I've ever seen in straight C.

If you want an even safer solution for when you're working in C++, take a look at Compile time sizeof_array without using a macro which describes a rather complex template-based method Microsoft uses in winnt.h.

like image 129
Michael Burr Avatar answered Sep 22 '22 14:09

Michael Burr