alignment of struct

TJB broughtj at gmail.com
Thu Mar 13 16:19:59 PDT 2014


I am a bit confused by the alignment of a struct in D.  I have 
some C++ code that I am translating into D.

Here is the C++:

#include <fstream>
#include <iostream>
#include <string.h>

struct TradesIdx
{
   char symbol[10];
   int tdate;
   int begrec;
   int endrec;
}__attribute__((packed));

struct TradesBin
{
   int ttim;
   int prc;
   int siz;
   short int g127;
   short int corr;
   char cond[2];
   char ex[1];
}__attribute__((packed));

int main()
{
   std::string 
infile("/Users/tyler/BFE/Measures/data/201212/T201212A.IDX");
   std::ifstream fin(infile.c_str(), std::ios::in | 
std::ios::binary);

   std::cout << "Size of TradesIdx = " << sizeof(TradesIdx) << 
std::endl;
   std::cout << "Size of TradesBin = " << sizeof(TradesBin) << 
std::endl;

   return 0;
}

Which when run gives the values:

Size of TradesIdx = 22
Size of TradesBin = 19

Here is the D code:

import std.stdio : writefln;
import std.stream;

align(1) struct TradesIdx
{
   char[10] symbol;
   int tdate;
   int begrec;
   int endrec;
}

align(1) struct TradesBin
{
   int ttim;
   int prc;
   int siz;
   short g127;
   short corr;
   char[2] cond;
   char[1] ex;
}

void main()
{
   string infile = 
"/Users/tyler/BFE/Measures/data/201212/T201212A.IDX";
   auto fidx = new File(infile, FileMode.In);

   writefln("Size of TradesIdx = %s", TradesIdx.sizeof);
   writefln("Size of TradesBin = %s", TradesBin.sizeof);
}

Which when run gives:

Size of TradesIdx = 24
Size of TradesBin = 19

Why the difference?  What is weird is that the two codes used to 
give the same answers. Has the alignment value of structs changed 
recently?


More information about the Digitalmars-d-learn mailing list