C++ Class/Structure size

☆樱花仙子☆ 提交于 2019-12-11 13:35:07

问题


Hi I have some problem about the size of a class/struct Here is my Graphnode.h, I only have 4 vars in it- one 16-unsigned char array, three unsigned char, I think the size should be 19. Why is it 32?

Graphnode currentNode; 
cout<< sizeof(currentNode)<<endl;// why this is 32 ?
cout<< sizeof(currentNode.state)<< endl;// this is 16

Graphnode.h:

#include <stdio.h>
#include <stdlib.h>
#include <tr1/array>

//using namespace std;
class Graphnode {

public:
    std::tr1::array<unsigned char, 16> state;
    unsigned char x;
    unsigned char depth;
    unsigned char direction;
    Graphnode(std::tr1::array<unsigned char, 16>,unsigned char,unsigned char, unsigned char);
    Graphnode();

};
Graphnode::Graphnode()
{
    int i=0;
    for(i=0;i<16;i++)
    {
       state[i] = 0;
    }
    x = 0;
    depth = 0;
    direction = 0;
}

Graphnode::Graphnode(std::tr1::array<unsigned char, 16> _state,unsigned char _x,unsigned char _d,unsigned char _direction)
{   
    int i=0;
    for(i=0;i<16;i++)
    {
       state[i] = _state[i];
    }
        x = _x;
        depth = _d;
        direction = _direction;
}

回答1:


Because the compiler does not lay out the data structure members one directly after the other; it also leaves padding in between.

Usually this means that any structure will be a multiple of some amount dependent on the types it contains and the target platform, even if the sum of the sizes of the fields is less.

All compilers typically offer non-standard extensions that let you control this packing to a lesser or greater degree.



来源:https://stackoverflow.com/questions/15078172/c-class-structure-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!