[try Beta version]
Not logged in

 
can not understand Sizeof result with a struct var

Apr 20, 2013 at 4:48pm
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 Apr 20, 2013 at 4:49pm
Apr 20, 2013 at 5:01pm
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.
Apr 20, 2013 at 5:06pm
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() 

Apr 20, 2013 at 5:11pm
Catfish3 wrote:
A common way to disable padding

Note that this relies on compiler extensions and is not standard C++.
Apr 20, 2013 at 5:27pm
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.
Apr 20, 2013 at 6:29pm
thank you guys .. reading about " padding" .made me figuring it out
Apr 20, 2013 at 6:31pm
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.
Apr 20, 2013 at 10:32pm
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 Apr 20, 2013 at 11:25pm
Topic archived. No new replies allowed.