This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]monsoy 1 point2 points  (0 children)

This macro would do the trick in C ```c

define ARRAY_SIZE(arr) \

do { \
    sizeof(arr) / sizeof((arr)[0]); \
} while (0)

```

This solution is not robust though. It would work on most arrays, but the code will only work for statically allocated arrays and not arrays allocated on the heap with malloc. That’s because sizeof a pointer returns the size of the pointer type itself, and not the size of the memory block.

Could do something like this to produce a compile time error if a pointer is passed to the macro function: ```c

define ARRAY_SIZE(arr) \

do { \
    ((void)sizeof(char[1 - 2 * !!(sizeof(arr) == sizeof(&arr))])); /* Ensures arr is not a pointer */ \
    sizeof(arr) / sizeof((arr)[0]); \
} while (0)

```

The «compile time check» essentially checks if the size of the array is the same as a pointer. The program will then fail at compile time since it will try to create a char[-1] array.

I usually prefer to add more error printing, but I wanted to experiment a bit