sizeof(struct) returns unexpected value

后端 未结 3 1482
轻奢々
轻奢々 2020-11-30 13:39

This should be simple but I have no clue where to look for the issue:

I have a struct:

struct region
{
public:
    long long int x;
    long long int         


        
3条回答
  •  死守一世寂寞
    2020-11-30 14:44

    As others said, structs are padded for alignments, and such padding not only depends on the type of the members, but also on the order of the members in which they're defined.

    For example, consider these two structs A and B as defined below. Both structs are identical in terms of members and types; the only difference is that the order in which members are defined isn't same:

    struct A
    {
        int i;
        int j;
        char c;
        char d;
    };
    
    struct B
    {
        int i;
        char c;
        int j;
        char d;
    };
    

    Would the sizeof(A) be equal to sizeof(B) just because they've same number of members of same type? No. Try printing the size of each:

    cout << "sizeof(A) = "<< sizeof(A) << endl;
    cout << "sizeof(B) = "<< sizeof(B) << endl;
    

    Output:

    sizeof(A) = 12
    sizeof(B) = 16
    

    Surprised? See the output yourself : http://ideone.com/yCX4S

提交回复
热议问题