tags:

views:

56

answers:

3

Greetings,

I'm able to find the size in bytes of a field after padding using the offsetof() macro.

Something like


struct a
{
  char r ;
  char s[ 255 ] ;
} ;

// the size in bytes of r after compiler padding is going to be
int lenR = offsetof( a, s ) - offsetof( a, r ) ;

But how can I find the size in bytes of the last field of a struct?

+1  A: 

I believe that the size of the first element of your struct is always going to be equal to sizeof(char) and the size of the second element of your struct will be sizeof(char[255]). Any padding that the compiler decides to insert is up to the compiler, and that memory doesn't belong to you. In other words, that memory is off limits to your application, and any attempt to use it may result in undefined behavior. That said, you can still always find (and will often need) the total size of the structure using sizeof(struct a). So the size of the fields are just what you would expect them to be, and the padding doesn't count toward the individual fields, even if it does increase the overall size of the struct.

Adam Batkin
+4  A: 

How about:

int lenS = sizeof(a) - offsetof(a, s);
1800 INFORMATION
Ack, you beat me to it by 20 seconds.
Jim Buck
+3  A: 

Padding isn't part of a particular field, it's part of the struct itself. If I have a struct like

struct foo {
   T1 v1;
         // <--- some padding here (A)
   T2 v2;
         // <--- some padding here (B)
   T3 v3;
};

Is the A padding part of v1? v2?. Is B part of v2? v3? If you are concerned about padding messing with doing things like persisting a struct to a file or similar, most (all?) compilers have a mechanism to disable structure padding, even on a struct by struct basis. To find out the size of the last member of your struct, in this case s, use sizeof, e.g.

 struct a tmp;
 size_t size = sizeof(tmp.s);

If you don't want to create a temporary you can take advantage of the fact that sizeof happens at compile time and doesn't do anything at runtime and do something like:

 namespace {
   const a& dummy_func();
 }
 size_t size = sizeof(dummy_func().s);

Dummy func doesn't need to be implemented ever.

Another option is

struct a {
   ...
   typedef char s_type[255];
   s_type s;
};
size_t size = sizeof(a::s_type);
Logan Capaldo