I need to find out the size any datatype in c++ without using the sizeof() function in the program.
I am a beginner in C++ programming.I hope this will work.Here i am using pointers.First create an array of which ever data type you want to want to find out.
[1]
.Click on code to see my code.Hope This will help.Happy Coding.Happy Day...:)
[1]: http://ideone.com/NEgZvm
Please note that sizeof
is not a function, it is an operator. There are few ways to approach to this problem depending upon the constraints. If we are allowed to declare objects of the said type things will be much easier. Then we can simply do:
int data;
printf("%u\n", (int)(&data+1)-(int)(&data));
Now if we are not allowed to create an object or pointer, then:
size_t Size = (size_t)(1 + ((D*)0));
where ‘D’ is the required data type (not a reference type) in question. This is however not a portable solution.
This SO question has few other approaches.
For calculating the size of the datatype of an array, It is very simple…
- int a[10];
- cout << int(&a[0]-&a[1]);
For calculating the size of normal variable its pretty difficult
So you are pointing 2 pointers to the array of the required datatype know?
and then subtracting the address difference??
Thanks
I was preparing for my interviewees…