You're not doing anything wrong, you just have to reset your expectations.
sizeof
evaluates to the size of the array in bytes, not the number of elements. You declared thisArray
to have 20 elements of type int
, and it's a good bet sizeof (int)
on your system is 4. Thus, the result of sizeof
on this object will be 80.
There's a trick to get the number of elements in an array:
size_t elements = sizeof myArray / sizeof myArray[0];
That is, you take the total size of the array (80 bytes) and divide by the size of a single element (4 in this case). Note that this trick will only work if the operand of the first sizeof
is an array type (that is, declared as T arr[N]
). If it's a pointer type, then this won't work - you'll be dividing the size of the pointer object by the size of an array element.