I'm looking for a macro similar to this: Compile-time assertion to determine if pointer is an array
The basic problem is sizeof(x) == 8
always (on a 64-bit compile) if x
is a pointer, while it could be many different values if x
is a statically allocated array.
But an array decays to a pointer, and an array could coincidentally have 8 bytes (e.g. a char
array sized to 8 or an int
array sized to 2).
The macro I would like is:
#define arr(x) x, sizeof(x)
The idea is to use in function calls, for example:
char str[1024];
.
.
func(str, sizeof(str));
becomes:
char str[1024];
.
.
func(arr(str));
The problem is it's easy for str
to be a pointer rather than true array. For example, you could mix up identifiers, or have a malloc()
'd array.
What should happen is if str
is not a statically allocated array, then there is a compile error. For example:
char str[1024];
func(arr(str)); /* works */
.
.
size_t size = 1024;
char *buf = malloc(size);
func(arr(buf)); /* compile error */
... and you must replace with:
size_t size = 1024;
char *buf = malloc(size);
func(buf, size); /* fixed bug */