Custom Sizeof Function
Use your knowledge of memory and element placements in arrays to create a sizeof function, that checks the size of a datatype by creating an array and comparing the memory location of its elements.
You can use templates to pass the datatype.
Hint
Function structure:
template <typename T>
int sizeOf() {
// Fill...
}
Pointer Arithmatic:
Do get the number of bytes between two elements you have to subtract the address of the first element from the address of the last. However, if you try subtracting two pointers of type T*, you will get the number of T elements between them. You can fix this by casting the pointers to a value like an int, or by casting the pointers to a datatype that takes up 1 byte, such as a char*.
Answer
#include <iostream>
#include <string>
template <typename T>
int sizeOf() {
T t[2];
return (char*)&t[1] - (char*)&t[0];
}
int main() {
std::cout << "char: " << sizeOf<char>() << " - " << sizeof(char) << std::endl;
std::cout << "short: " << sizeOf<short>() << " - " << sizeof(short) << std::endl;
std::cout << "int: " << sizeOf<int>() << " - " << sizeof(int) << std::endl;
std::cout << "long: " << sizeOf<long>() << " - " << sizeof(long) << std::endl;
std::cout << "long long: " << sizeOf<long long>() << " - " << sizeof(long long) << std::endl;
std::cout << "float: " << sizeOf<float>() << " - " << sizeof(float) << std::endl;
std::cout << "double: " << sizeOf<double>() << " - " << sizeof(double) << std::endl;
std::cout << "long double: " << sizeOf<long double>() << " - " << sizeof(long double) << std::endl;
std::cout << "std::string: " << sizeOf<std::string>() << " - " << sizeof(std::string) << std::endl;
}
Great! Now that you know how to check the size of a datatype like this, never do this. This task was just a puzzle. This function doesn't have a practical use over sizeof.