For the given array:
int array[10];
What is the difference between
sizeof array / sizeof *array
and
sizeof array / sizeof array[0]
when calculating the number of elements in array
?
Basically, “array” is a “pointer to the first element of array” but “&array” is a “pointer to whole array of 5 int”. Since “array” is pointer to int, addition of 1 resulted in an address with increment of 4 (assuming int size in your machine is 4 bytes).
a is an array of type int[6] , therefore &a is a pointer-to-array of type int (*)[6] , and &a[0] is a pointer to the first element of a , so it's a int * .
(&array)[1] would be the next array of 16 integers, if there was one. If you do array[0] , the value you end up with is an integer, which you can't subscript again. array[1] is just the next integer.
There is none in this case. Both ultimately results in the type int
because in the first case array decays into pointer to the first element when used as an operand of *
(You are dereferencing a int*
).
Note one thing - you might have heard that on sizeof
there is no decay of arrays but here the decay happens when array is used as operand to *
. The operand for sizeof
is simply int
. (Discussing about sizeof arr/sizeof *arr
)
In case you want to get a clear idea - try this
int a[10][20];
printf("%zu %zu\n",sizeof a/ sizeof *a, sizeof a/ sizeof **a);
Your second case is WYSIWYG type of thing - what I mean by this, it just says total size of the array and divide it with what it contains (the size of it). And yes it would return the size of the array. That is what is being done.
arr[0]
is nothing but *(arr+0)
means *arr
. So that makes sense and they are same.
Few points that will clarify things (If you later use sizeof
)
array
and &array[0]
is same in this context. Their value and type both will be same. But For pointers being the same value is just one thing - their implication on the pointer arithmetic is a whole different story.
int a[10][20];
Here a
and &a
and a[0]
all has same value but their type is different and since pointer arithmetic is closely coupled with what it points to. It matters.
The expression array[n]
is by definition the same as *(array + n)
The expression array + 0
is by definition the same as array
(unless array
is an operand of sizeof
).
So yes, array[0]
and *array
are the same.
This is much more than is needed in this case. For arguments of sizeof
only the type matters, and it is certainly the same for both expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With