int a[17];
size_t n = sizeof(a) / sizeof(int);
In C it is most common to find a length of an array like this and it is pretty clear. My question though is that the following wouldn't work:
int days[] = {1,2,3,4,5};
int *ptr = days;
size_t n = sizeof(ptr) / sizeof(int);
What I suppose is happening here is that ptr is just a normal 8-byte address pointing to the first element of the array, so it won't give us the real length of the array. But in the first example, sizeof(a), a is also just a pointer pointing to the first element of the array. So what is the difference here and why does one work but the other not?
ais not a pointer- it's an array.ptris a pointer butdaysis an arrayais of typeint[17], which is statically known to the compiler; this type decays toint*in many contexts, but not all, andsizeofis one of the non-decaying contexts. The compiler in general can't know whatptris pointing to. (In this example, an optimising compiler could probably infer that it points to length-5 arraydays, but imagine ifptrwas changed around in various complicated ways between this initial assignment and thesizeof ptr.)