| ??? 04/30/08 23:03 Modified: 04/30/08 23:06 Read: times |
#154235 - Determining object sizes - at run time Responding to: ???'s previous message |
Although the compiler MUST know the number of bits for addresses, registers etc. during the compile time there is a way to find this out during runtime.
As said the compiler knows the sizes already so propably the simplest solution would be:
printf( "Size of integer is %d\n", sizeof(int) );
However, if You want to fiddle around with data alignment and sizes, hopefully to learn something, here is a way to do this at runtime: 1. Declare an union with large enough character array and the data type(s) You want to know the sizes and alignment of. 2. Assign a known value to the datatype (not the char array) 3. Inspect the character array to determine size and also data alignment So Your code would be like this (intentionally left off the comments):
typedef union inspector_u {
char chararray [16];
int inspectint;
short inspectshort;
long inspectlong;
} inspector_t;
int main ( int aAc, char ** aAv ) {
inspector_t inspector;
// Why not just simple assign ?
memset( &inspector, 0, sizeof( inspector ) );
// Why just -1 ?
inspector.inspectint = -1;
// Here comes the code that checks the chararray
// figure it out Yourself.
return 0;
}
After detecting the object size You can start detecting the order of bytes in it. Notice that most compilers do NOT tell this directly. There are some fancy defines but nothing can replace knowledge learned the hard way. |
| Topic | Author | Date |
| find the size of processor | 01/01/70 00:00 | |
| C is not that portable! | 01/01/70 00:00 | |
| thanks but could u clarify | 01/01/70 00:00 | |
| I think you missed the point | 01/01/70 00:00 | |
| Various compilers different results | 01/01/70 00:00 | |
| Word size - not code size? | 01/01/70 00:00 | |
| u r correct | 01/01/70 00:00 | |
| Determining object sizes - at run time | 01/01/70 00:00 | |
| Not quite | 01/01/70 00:00 | |
| Correct ! | 01/01/70 00:00 | |
| not sure what you would do with the information | 01/01/70 00:00 | |
| This was an interview question | 01/01/70 00:00 | |
| More trick interview questions | 01/01/70 00:00 | |
| I found the solution, Andy , Neil please comment | 01/01/70 00:00 | |
| Great! Now do it in C | 01/01/70 00:00 | |
| Same logic for C and asm | 01/01/70 00:00 | |
| No, it isn't. | 01/01/70 00:00 | |
| What would be the point? | 01/01/70 00:00 | |
| It is worse than that | 01/01/70 00:00 | |
| the whole question is silly | 01/01/70 00:00 | |
| It can even get this silly... | 01/01/70 00:00 | |
It is an interview question | 01/01/70 00:00 |



