Implement Our Own sizeof( )
Using custom user-defined sizeof function which can provide the functionality same as sizeof( ).
C++ Program to Implement Custom User-Defined sizeof Function
C++
// C++ program to find size of // an array by writing our // own sizeof operator #include <iostream> using namespace std; // User defined sizeof macro #define my_sizeof(type) \ (( char *)(&type + 1) - ( char *)(&type)) int main() { int arr[] = { 1, 2, 3, 4, 5, 6 }; int size = my_sizeof(arr) / my_sizeof(arr[0]); 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)
To know more about the method refer to Implement our own sizeof.
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