I was searching for a way to find the size of an array in C without using sizeof and I found the following code:
int main ()
{
int arr[100];
int arry[6]={1,2,3,4,5,6} //lets array elements be 6, so... size in byte = (char*)(arry+6)-(char *)(arry)=24;
&arr gives you a pointer to the array. (&arr)[1] is equivalent to *(&arr + 1). &arr + 1 gives you a pointer to the array of 100 ints that follows arr. Dereferencing it with * gives you that array that follows. Since this array is used in an additive expression (-), it decays to the pointer to its first element. The same happens to arr in the expression. So you subtract to pointers, one pointing to the non-existent element right after arr and the other pointing to the first element of arr. This gives you 100.
But it's not working. %d is used for int. Pointer difference returns you ptrdiff_t and not int. You need to use %td for ptrdiff_t. If you lie to printf() about the types of the parameters you're passing to it, you get well-deserved undefined behavior.
EDIT: (&arr)[1] may cause undefined behavior. It's not entirely clear. See the comments below, if interested.
&variable gives location of the variable (call it as P)
&variable + 1 gives address of the location next to the variable. (call it as N)
(char*)N-(char*)P gives how many characters are there between N and P. Since each character is 1 byte sized, so the above result gives the number of bytes P and N. (which equals to the size of array in bytes).
Similarly,
(char*) (a+1)-(char*)a; gives size of each element of the array in bytes.
So the number of elements in the array = (size of array in bytes)/(size of each element in the array in bytes)
#include<stdio.h>
int main()
{
int a[100];
int b = ((char*)(&a+1)-(char*)(&a));
int c = (char*) (a+1)-(char*)a;
b = b/c;
printf("The size of array should be %d",b);
return 0;
}
int main ()
{
int arr[100];
printf ("%d\n", ((char*)(&arr+1) - (char*)(&arr))/((char*) (arr+1) -(char*) (arr)));
return 0;
}
Generally (as per visual studio),
for an array &arr is same as arr ,which return the starting base address of our function.
(&arr)[0] is nothing but &arr or arr
ex: it will return some address : 1638116
Now, (&arr)[1] means we are started accessing the array out of bounce means next array or next segment of the size of present array(100 ahead).
ex: it will return some address : 1638216
Now, subtracting (&arr)[1] - (&arr)[0]=100
&arr is a pointer to an array of 100 ints.
The [1] means "add the size of the thing that is pointed to", which is an array of 100 ints.
So the difference between (&arr)[1] and arr is 100 ints.
(Note that this trick will only work in places where sizeof would have worked anyway.)