There is a well known pattern of figuring out array length:
int arr[10];
size_t len = sizeof(arr) / sizeof(arr[0]);
assert(len == 10);
T
In general case, if I'm missing something, dereferencing a null pointer under sizeof
can lead to undefined behavior. Since C99, sizeof
is not a purely compile time construct. The operand of sizeof
is evaluated at run-time if the operand type is a VLA.
Consider the following example
unsigned n = 10;
int (*a)[n] = NULL; // `a` is a pointer to a VLA
unsigned i = 0;
sizeof a[i++]; // applying `sizeof` to a VLA
According to the C99 standard, the argument of sizeof
is supposed to be evaluated (i.e. i
is supposed to get incremented). Yet I'm not entirely sure that the null-point dereference in a[0]
is supposed to produce undefined behavior here.