Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of arbitrary array type in C function

Tags:

arrays

c

sizeof

I'd like to replace the following macro with an actual function in C.

#define ARRAY_LENGTH(a) (sizeof(a)/sizeof((a)[0]))
like image 235
krithik Avatar asked Jul 24 '26 02:07

krithik


2 Answers

Keep your macro. Replacing it is a mistake. When you pass an array to a function it decays into a pointer and you lose size information.

like image 98
T Johnson Avatar answered Jul 26 '26 03:07

T Johnson


As others have said, you can't.


When you pass an argument to a function, the value of that expression is copied into a new object.

One problem is functions can't have arrays as arguments. Array declarations in function prototypes are converted to pointer declarations.

Similarly, the expression denoting the array that you're passing will be converted to a pointer to the first element of the array.

Another problem standing in your way is that C has no generic functions. There is no way to provide a function with an "array of T", where T can be any type you like, aside from using a void * parameter and passing size information separately.


Function-like macros as expanded at a different stage, however. They're translated during compilation; imagine copying and pasting the code for the macro everywhere it's mentioned, substituting the arguments, prior to compilation. That's what your compiler does with macros.

For example, when you write printf("%zu\n", ARRAY_LENGTH(foo)); it replaces this with: printf("%zu\n", (sizeof(foo)/sizeof((foo)[0])));.


P.S. sizeof is not a function; it's an operator... Coincidentally, it is one of the few (the others being the &address-of operator and the newly adopted _AlignOf operator) which don't cause the array expression to be converted to a pointer expression.

like image 45
autistic Avatar answered Jul 26 '26 05:07

autistic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!