#include <stdio.h>
int main(void) {
int TEST_HB[10];
memset(TEST_HB,'9', sizeof( TEST_HB));
printf("%c\n",TEST_HB[9]);
printf ("TEST_HB[10]=%d\n",sizeof( TEST_HB[40])); // shows 4
printf ("Arraysize=%d\n",(sizeof(int)*10)); // gets the expectected results
return 0;
}
I believe that sizeof (myArray) should return the total size of the array in bytes. But why does sizeof( TEST_HB[40]) returns 4 when it is not defined ?
TEST_HB[40]is an expression with typeint(and undefined behavior if evaluated, since40is too big for the array). Sosizeof(TEST_HB[40])is the size of aninton your implementation: 4 is typical.Importantly,
sizeofdoes not evaluate its operand unless it’s a VLA — it just uses the type. Therefore your code has defined behavior even though there’s no such object asTEST_HB[40].Actually, I say it has defined behavior, but
sizeofevaluates to typesize_t, which isn’t printed with%d. Use%zuwhere available or consult your compiler documentation. You’ve got away with it here because you’ve got lucky with the varargs calling convention, plus eithersize_tis the same size asintin your implementation, or your implementation is little-endian, or both.A fairly common use of the fact that
sizeofdoes not evaluate the operand is to write something like this:sizeof(*foo)is the same assizeof(struct Foo), but to some people it’s more “obviously” the right size to use.foois uninitialized before the memory is allocated, so it’s just as well thatsizeofdoesn’t actually use the value offoo.A less common use, that demonstrates the behavior of
sizeof: