Is there a standard function in C that would return the length of an array?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Often the technique described in other answers is encapsulated in a macro to make it easier on the eyes. Something like:
Note that the macro above uses a small trick of putting the array name in the index operator (‘
[]‘) instead of the0– this is done in case the macro is mistakenly used in C++ code with an item that overloadsoperator[](). 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:
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.