I was googling a solution to find out the length of an array in C++. One of the solutions I found is this
int arr[] = {1,2,3,4,5,6};
int size = *(&arr+1)-arr; //size is the length of the array
I was confused between &arr
and arr
since both give the base address of the array. Googled again and found that &arr + 1
gives the address of next block of memory that is not part of the array where arr + 1
gives the address of next element in the array.
I have written the following code to test out the difference between &arr
and arr
:
int arr[] = {1,2,3,4,5,6};
printf("value of &arr + 1 - &arr = %d\n", &arr + 1 - &arr);
printf("value of *(&arr + 1) - arr = %d\n", *(&arr + 1) - arr);
The answer to the first printf
is 1
where as the second printf
gives 6
. This is the part that confuses me: Since both &arr
and arr
hold the base address of the same array, why are the results different?
Since both "&arr" and "arr" hold the base address of the same array, why are the results different?
Because the type is different. Pointer arithmetic is affected by the type of the pointer, and more specifically, the type of the pointed object.
&arr
is a pointer to an array of 6 int. Adding 1 to that increments to the next array of 6 ints (if it was an element of an array of arrays).
arr
, although is an array, decays to pointer to the first element of the array when its value is used, such as in the pointer arithmetic expression. The decayed value is a pointer to an int and adding 1 to that moves the pointer to the next integer.
P.S. You can use std::size
instead. Or std::extent
pre-C++17. Or sizeof arr / sizeof *arr
pre-C++11.
*(&arr + 1) - arr
probably works, but technically indirects through a past-the-end pointer (to an object which does not exist), which is typically undefined behaviour. I'm not sure whether there might be some exception to the rule considering the value is only used to decay to a pointer.
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