Home > Mobile >  How to align a structure correctly?
How to align a structure correctly?

Time:09-23

I am trying to align a structure using the directive (#pragma pack).

I need it has 112 bytes in size. (14*8=112 bytes).

However it has 80 bytes only.

How to do it correctly?

#pragma pack (8)
struct Deal
{
   long     deal_ticket;         
   long     order_ticket;        
   long     position_ticket;     
   long     time;                
   long     type;                
   long     entry;                
   char     symbol[8];           
   double   volume;              
   double   price;               
   double   profit;              
   double   swap;                
   double   commission;          
   long     magic;               
   long     reason;              
};


int main()
{
    cout << sizeof(Deal) << endl;
}

Thank you so much!!

CodePudding user response:

I need it has 112 bytes in size. (14*8=112 bytes).

long is only guaranteed to be at least 32 bits which is 4 bytes (assuming 8 bit byte); not 8 bytes.

If you want each integer to be 64 bits, then you can use std::int64_t instead of long.

#pragma pack never increases the size of a class. It only ever decreases the size by removing padding that is otherwise required for alignment.

P.S. #pragma pack doesn't exist in standard C (in fact, no standard pragmas exist in C ). It is a language extension.

  • Related