size of a datatype without using sizeof

Solution 1:

To my mind, this fits into the category of "how do I add two ints without using ++, += or + ?". It's a waste of time. You can try and avoid the monsters of undefined behaviour by doing something like this.

size_t size = (size_t)(1 + ((X*)0));

Note that I don't declare a variable of type or pointer to X.

Solution 2:

Look, sizeof is the language facility for this. The only one, so it is the only portable way to achieve this.

For some special cases you could generate un-portable code that used some other heuristic to understand the size of particular objects[*] (probably by making them keep track of their own size), but you'd have to do all the bookkeeping yourself.

[*] Objects in a very general sense rather than the OOP sense.

Solution 3:

Well, I am an amateur..but I tried out this problem and I got the right answer without using sizeof. Hope this helps.. I am trying to find the size of an integer.

int *a,*s, v=10;

a=&v;

s=a;

a++;

int intsize=(int)a-(int)s;

printf("%d",intsize);

Solution 4:

The correct answer to this interview question is "Why would I want to do that, when sizeof() does that for me, and is the only portable method of doing so?"

Solution 5:

The possibility of padding prevent all hopes without the knowledge of the rules used for introducing it. And those are implementation dependent.