简体   繁体   中英

Length of arbitrary array type in C function

我想用C中的实际函数替换下面的宏。

#define ARRAY_LENGTH(a) (sizeof(a)/sizeof((a)[0]))

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.

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]))); .


PS 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 .

int arraySz(void **a)
{ 
return(sizeof(a[])/sizeof(a[][]));
}

However a would have to be pointing to an existing rectangular array, not just be a pointer to a pointer, or return value from malloc() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM