can not understand Sizeof result with a struct var

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
typedef struct Element Element;
struct Element
{
    char x;
    double* y;
};


int main()
{
    Element a;

    printf("%d\n",sizeof(Element ));
    return 0;
}

this one with y pointer gives 8

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
typedef struct Element Element;
struct Element
{
    char x;
    double y;
};


int main()
{
    Element a;

    printf("%d\n",sizeof(Element ));
    return 0;
}


ths one with a normal y variable gives 12
Last edited on
Your pointers are probably 4 bytes (try doing sizeof(double*))
Your doubles are probably 8 bytes (try doing sizeof(double))

The single char is 1 byte, but the struct will get padded up to the nearest 4-byte boundary for alignment reasons.
Member data in structures and classes is often word-aligned, for performance reasons.
This means there's padding (unused space) between your member data x and y.

A common way to disable padding is:
1
2
3
4
5
6
7
#pragma pack(1)
struct Element
{
    char x;
    double y;
}
#pragma pack() 

Catfish3 wrote:
A common way to disable padding

Note that this relies on compiler extensions and is not standard C++.
Note that this relies on compiler extensions and is not standard C++.

You're welcome to show a standard C++ method, if there is one.
thank you guys .. reading about " padding" .made me figuring it out
Note that this relies on compiler extensions and is not standard C++.


Also note that this is likely to deteriorate performance. Things are padded for a reason.
could also simply crash ( on certain non-Intel platforms )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

#pragma pack(1)
struct Element
{
    char x;
    double y;
};
#pragma pack()

int main()
{
    Element e = {'a', 3.14};
    std::cout << "Size of Element is " << sizeof e << '\n'
              << "Enter a double: ";
    std::cin >> e.y;
    std::cerr << e.y << '\n';
}
$ ./test
Size of Element is 9
Enter a double: 1.23
Bus Error
Last edited on
Topic archived. No new replies allowed.