How to use Pointer Hack In C++
The following solution is concise when compared to the other solution. The number of elements in an array A can be found using the expression:
// &arr returns a pointer int size = *(&arr + 1) - arr;
How Does this Method Work?
Here the pointer arithmetic does its part. We don’t need to explicitly convert each of the locations to character pointers.
- &arr – Pointer to an array of 6 elements. [See this for difference between &arr and arr]
- (&arr + 1) – After adding 1 to the address of array of 6 integers, the pointer will point to the memory location immediately after the end of the array.
- *(&arr + 1) – Same address as (&arr + 1), but type of pointer is “int *”.
- *(&arr + 1) – arr – Since *(&arr + 1) points to the address 6 integers ahead of arr, the difference between two is 6.
C++ Program to Find the Size of an Array Using Pointer Hack
C++
// C++ program to find size // of an array by using a // pointer hack #include <iostream> using namespace std; int main() { int arr[] = { 1, 2, 3, 4, 5, 6 }; int size = *(&arr + 1) - arr; cout << "Number of elements in arr[] is " << size; return 0; } |
Output
Number of elements in arr[] is 6
Complexity Analysis
- Time complexity: O(1)
- Auxiliary space: O(1)
How to Find Size of an Array in C++ Without Using sizeof() Operator?
In C++, generally, we use the sizeof() operator to find the size of arrays. But there are also some other ways using which we can find the size of an array. In this article, we will discuss some methods to determine the array size in C++ without using sizeof() operator.
Contact Us