sizeof(a)
is the size of the full array
sizeof(*a)
is the size of one element of the array, *a
being the first element of the array, equivalent of a[0]
this is why you need to divide sizeof(a)
by sizeof(*a)
to have the number of elements
If you have an array of char
because by definition sizeof(char)
is 1 you do not need to divide by the size of an element, else you need.
For instance having an array of 10 int
and supposing sizeof(int)
is 4 the size of the array is 10*4=40, which is not the number of elements => you need to divide by the size of an element
int a[10];
std::cout << sizeof(a) << std::endl; // print 40 supposing sizeof(int) is 4
std::cout << sizeof(*a) << std::endl; // print 4 supposing sizeof(int) is 4
std::cout << (sizeof(a)/sizeof(*a)) << std::endl; // print 10 expected
Note to use sizeof(*a)
is better than to use sizeof(int)
because in case you change the type of the array sizeof(*a)
will be still valid