As I wrote earlier, sizeof
isn't a function; it's an operator, and a special kind of operator where the argument isn't evaluated for its value, hence the reason sizeof *(char *)NULL
is perfectly valid and doesn't cause segfaults. This should be pointed out in the interview.
Furthermore, this question is a waste of time, also a fact that should be pointed out to the interviewer. At that point I'd be walking out the door, and off to a more sensible interview. You probably don't want to work for this company, if they commonly chase such pointless exercises.
Having said that, one who is entertained by this might come to the conclusion that the offsetof
macro could be useful. Form a struct
containing the given type and a dummy element, then use offsetof
to determine what the offset of the dummy element is.
#include <stddef.h>
#include <stdio.h>
#define my_sizeof(x) ((size_t) offsetof(struct { x fu; char ba; }, ba))
int main(void) {
printf("my_sizeof (char): %zu\n", my_sizeof(char));
printf("my_sizeof (void *): %zu\n", my_sizeof(void *));
}
Note that behind the scenes the offsetof
macro may use pointers. The only alternative I see is using the &
address-of operator (e.g. this question), not to be confused with the bitwise &
operator (which I think you and/or your interviewer is doing, also to be pointed out); this violates your requirements as that definitely uses a pointer.
Then again, if you can't use pointers at all, then you rule out arrays and function calls; the entire language is rendered virtually useless by that requirement.