By the statement int a[7]
, you are declaring an array of integers of size 7 (Only 7 integer elements can be stored here).
If you use the statement sizeof(a)
, you get the size of a. As you probably may know, it is 7 x 4
. (Why 4? Because the size of an integer is 4 bytes). Therefore, if you need to get the real size of the array (i.e. the number of elements), you must divide it with the size of int
.
Why do I have to use (sizeof(a)/sizeof(*a))
to receive the right size, and why does sizeof(*a)
returns 4, but sizeof(a)
returns 28?
To answer this, you must be aware that the array name is actually a pointer to the 1st element of the array (i.e. In this case, it points at a[0]
.) So, what is a[0]
? It is an integer right? You can think of sizeof(*a)
as sizeof(int)
.
Since sizeof(int)
returns 4
, so will sizeof(*a)
.
The reason why you get 7 (the correct answer) is because:
sizeof(a) = 7 * 4
,
sizeof(*a) = 4
, therefore
(sizeof(a)/sizeof(*a)) = 7
.