How to find the size of an object/datatype without using sizeof operator ?
Since
sizeof is an in-built operation, there should be no reason why a method to compute size would need to be user-defined. So, at best, this question is of theoretical importance.
Size of object without using sizeof operator:
To find the size of an object obj (say), we could use:
size_t size_obj = (char*)(&obj + 1) - (char*)(&obj);
The principle behind this computation is simple. (&obj + 1) is guaranteed to be well defined and always points sizeof(obj) bytes beyond obj. So, subtracting the address of obj from (&obj + 1) would give sizeof(obj). The (char*) typecast is necessary to ensure that the difference is given in terms of bytes.
Example:
struct mystruct
{
int i;
char data
[5];
}obj;
int main
()
{
size_t size=
(char*
)(&obj +
1) -
(char*
)(&obj
);
printf("Size of mystruct object= %lu\n",
(unsigned long)size
);
return 0;
}
Size of type without using sizeof operator:
For basic integer types, it would be as simple as looking up the range of the type in limits.h, and computing the number of bits in use based on the range. For example, if UINT_MAX is 65535 and UINT_MIN is 0, size of unsigned int would be 16 bits, since 16 bits would be sufficient to represent 65535. For signed types, one extra bit would be required. This, of course, assumes that there are no padding bits in use. But padding bits are a rarity; so this computation would give the correct size most of the time, and atleast a 'close-enough' size all the time.
Alternately, we could declare a temporary object of the relevant type, and find the size using the computation used in the previous section.
Another method suggested often is to use:
size_t size_type = (char*)((type*)0 + 1) - (char*)(type*)0;<<
The principle behind this computation is the same as in the previous section. A phantom object of the type under consideration is assumed to be present at the location that a null pointer points to. Then 1 is added to make the pointer point sizeof(type) bytes beyond the phantom object and the phantom objects address is subtracted to get the size of the type.
This method does seem to give the correct size on most systems. But it is not fully portable.
Example:
int main
()
{
size_t size=
(char*
)((int*
)0 +
1) -
(char*
)(int*
)0;
printf("Size of int = %lu\n",
(unsigned long)size
);
return 0;
}
CategoryPuzzles
CategoryPointers