function that calculate Size of Structure without

2019-08-03 10:22发布

问题:

Hi i want to make a function which calculate the size of structure without padding bytes.

Example :

struct test{
    int   x;
    char  y;
    int   z;
};

If i calculate the size of above structure i must get 9 byte (i.e. without padding bytes)

And consider the case where i might not know the variable present in struct.

Example :

struct test{
    int   x;
    ....
    ....
    ....
    int   z;
};

so if i calculate the size it should give correct size.

Is it possible do write such function?I tried reading on structure's but i dint find any solution.I saw there is some compiler option are present from that i can get but i dont want any in build compiler option.

回答1:

No, C doesn't have enough introspection to make this possible. At run-time, there is no information left that the program can use to "know" which fields are in a structure, or what their types are.



回答2:

The sizeof compiler construct should give you the size of the object "as the compiler sees it". Most compilers will align structures on 4 byte boundaries for efficient memory access at the expense of space. Try

#include <stdio.h>
int main() {
  struct test{
    int x;
    char a;
    int y;
  };
  struct test myStruct;
  printf("size of myStruct is %ld\n", sizeof(myStruct));
}

When I run it, I get

size of myStruct is 12

Which shows that my compiler, in this situation, is allocating four bytes to 'a'. I think that's your answer... unless I really misunderstood your question, and in particular your "without padding bytes" comment.

Rewriting the definition of the struct as:

  struct test{
    int x;
    char a;
    int y;
  }__attribute__((packed));

The output becomes

size of myStruct is 9

This only works at compile time - so it is not really a "function". And it doesn't apply if you don't know your struct at compile time. As such, I think my answer and the one given by @unwind above are not inconsistent.



标签: c++ c struct