2

I'm new to c language.I want to know how to align members of a structure with 1 byte option.There are three structures.I want to save objects created from structures in a file.I will appreciate any answer which can help me.I posted the code here.Thanks to all!

    struct AddressTmpl
{
   char sStreet[51];
   char sCity[51];
   char sCountry[51];
};

enum Gender
{
   Male     = 1,
   Female   = 2
};

struct PersonTmpl
{
   int nPersonID;

   char chRecordType;
#define REC_TYPE_PERSONAL  1
#define REC_TYPE_HOME      2
#define REC_TYPE_WORK      3

   union
   {
      struct /* record type 1 */
      {
         char sFirstName[31];
         char sLastName[32];
         char sBirthdate[11]; /* YYYY/MM/DD date format */
         Gender theGender;
      }PersonalInfo;

      struct /* record type 2 */
      {
         struct AddressTmpl homeAddress;
         char sPhone[31];
         char sEmail[51];
      }HomeDetails;

      struct /* record type 3 */
      {
         char sCompany[51];
         struct AddressTmpl workAddress;
         char sPhone[31];
         char sFax[31];
         char sEmail[51];
      }WorkDetails;
   }Details;
};
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
Lucy
  • 29
  • 1
  • 1
    XY-problem. Define a clear file-format and serialise the `struct` by fields. Don't just dump memory blocks to a file. Best use a text-format. – too honest for this site Nov 24 '16 at 22:43
  • And which language of the two **different** languages C and C++ do you use? – too honest for this site Nov 24 '16 at 22:44
  • i am using c language – Lucy Nov 24 '16 at 22:45
  • I would suggest taking a look [here](http://en.cppreference.com/w/c/language/_Alignas) for information about how to specify alignment in C. As @Olaf said, though, this is an XY problem (how to align fields, so you can write the data to file), and your time may be better spent attacking Y (how you want to write the data to file) directly. – Justin Time - Reinstate Monica Nov 24 '16 at 22:48
  • You could also look at [`#pragma pack`](http://stackoverflow.com/questions/3318410/pragma-pack-effect), [`__attribute__((packed, aligned(N)))`](http://stackoverflow.com/questions/11770451/what-is-the-meaning-of-attribute-packed-aligned4), or platform-specific equivalents thereof Again, though, it may be better to go after the problem directly. – Justin Time - Reinstate Monica Nov 24 '16 at 22:53
  • That kind of thing is platform/compiler specific, and I don't know what you are using so the best I can say is, look in your compiler documentation. – Stuart Nov 25 '16 at 03:24

0 Answers0