so i was just playing around with the code to find array length.... the orignal code was:
#include<stdio.h>
int main()
{ int al;
int a[] = {1,2,3,4,5};
al= sizeof(a) / sizeof(a[0]);
printf("%d",al);
return 0;
}
which gave me the output of:
5
but when i changed the expression to:
al= sizeof(&a[0]) / sizeof(a[0]);
it gave me the output of
2
if a
is the same as &a[0]
...then why does this happen?
Also, if put &a
in place of &a[0]
the answer is also 2.
No, they differ in type.
For context of sizeof
operator, a
is of type int [5]
, but , &a[0]
is of type int *
. They are indeed of different size. Following the same analogy, &a
is of type int (*)[5]
- basically, a pointer.
So, for the expression
al= sizeof(a) / sizeof(a[0]);
is the same as
al= sizeof( int [5]) / sizeof(int);
which gives you 5. On the other hand,
al= sizeof(&a[0]) / sizeof(a[0]);
is the same as
al= sizeof(int *) / sizeof(int);
now, it appears, in your platform, sizeof(int *)
is 8 and sizeof(int)
is 4, so you get to see a result of 2.
Remember, in some cases, array type decays to a pointer to the first element of the array, but one of the exceptional cases where is does not, is when the array is used as the operand of sizeof
operator.