title: struct padding influence in C struct serialization ( saving to file )
body: <p>I have the following structs in C:</p>
  
  <pre><code>typedef struct sUser {
      char name[nameSize];
      char nickname[nicknameSize];
      char mail[mailSize];
      char address[addressSize];
      char password[passwordSize];
      int totalPoints;
      PlacesHistory history;
      DynamicArray requests;
  }User;
  
  typedef struct sPlacesHistory {
      HistoryElement array[HistorySize];
      int occupied;
      int last;
  }PlacesHistory;
  </code></pre>
  
  <p>and the functions:</p>
  
  <pre><code>void serializeUser( User * user, FILE * fp ) {
      fwrite( user, nameSize + nicknameSize + mailSize + addressSize + passwordSize + sizeof( int ) + sizeof( PlacesHistory ), 1, fp );
      serializeDynamicArray( user -&gt; requests, fp );
  }
  
  User * loadUser( FILE * fp ) {
      User * user = malloc( sizeof( User ) );
      fread( user, nameSize + nicknameSize + mailSize + addressSize + passwordSize + sizeof( int ) + sizeof( PlacesHistory ), 1, fp );
      user -&gt; requests = loadDynamicArray( fp );
  
      return user;
  }
  </code></pre>
  
  <p>When I load the struct User, and I print that user (loaded from file), the field "last" of placesHistory has the value of 255 or -1, depending on the order of the fields of the PlacesHistory structure. But The User I saved had -1 on that member.</p>
  
  <p>So when i get 255, it is obviously wrong.. 
  I suspect this has to do about struct padding.</p>
  
  <p>How can I do this in such a way that the order of fields in the structure doesn't matter?<br>
  Or which criteria do I need to follow to make things work right?<br>
  Do I need to fwrite/fread one member at a time? ( I would like to avoid this for efficiency matters )<br>
  Do I need to serialize to an array first instead of a file? (I hope not .. because this implicates to know the size of all my structures beforehand because of the mallocated array- which means extra work creating a function for every non simple structure to know it's size)  </p>
  
  <p>Note: *Size are defined constants<br>
  Note2: DynamicArray is a pointer to another structure.</p>