title: Casting from bigger datatype (struct) to smaller one
body: <p>I already knew pointer of a struct can be cast to another pointer of a struct with equivalent memory layout. </p>
  
  <p>However, in the following piece of code:</p>
  
  <pre><code>#include &lt;string.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netinet/in.h&gt;
  
  #define MYPORT "3490"  // the port users will be connecting to
  #define BACKLOG 10     // how many pending connections queue will hold
  
  int main(void)
  {
      struct sockaddr_storage their_addr;
      socklen_t addr_size;
      struct addrinfo hints, *res;
      int sockfd, new_fd;
  
      // !! don't forget your error checking for these calls !!
  
      // first, load up address structs with getaddrinfo():
  
      memset(&amp;hints, 0, sizeof hints);
      hints.ai_family = AF_UNSPEC;  // use IPv4 or IPv6, whichever
      hints.ai_socktype = SOCK_STREAM;
      hints.ai_flags = AI_PASSIVE;     // fill in my IP for me
  
      getaddrinfo(NULL, MYPORT, &amp;hints, &amp;res);
  
      // make a socket, bind it, and listen on it:
  
      sockfd = socket(res-&gt;ai_family, res-&gt;ai_socktype, res-&gt;ai_protocol);
      bind(sockfd, res-&gt;ai_addr, res-&gt;ai_addrlen);
      listen(sockfd, BACKLOG);
  
      // now accept an incoming connection:
  
      addr_size = sizeof their_addr;
      new_fd = accept(sockfd, (struct sockaddr *)&amp;their_addr, &amp;addr_size);
  
      // ready to communicate on socket descriptor new_fd!
      .
      .
      .
  </code></pre>
  
  <p><code>struct sockaddr_storage their_addr</code> is cast to <code>(struct sockaddr *)&amp;their_addr</code>. The layout of each struct is:</p>
  
  <pre><code>struct sockaddr {
      unsigned short    sa_family;    // address family, AF_xxx
      char              sa_data[14];  // 14 bytes of protocol address
  }; 
  </code></pre>
  
  <p>and:</p>
  
  <pre><code>struct sockaddr_storage {
      sa_family_t  ss_family;     // address family
  
      // all this is padding, implementation specific, ignore it:
      char      __ss_pad1[_SS_PAD1SIZE];
      int64_t   __ss_align;
      char      __ss_pad2[_SS_PAD2SIZE];
  };
  </code></pre>
  
  <p>socktaddr_storage is definitely a bigger information storage, so it can be cast to whatever smaller than it to fit a function declaration. Inside the function, it does not matter what type of struct is, as long as the passed struct into the function has enough memory blocks for the function to operate as the required struct. Is this correct?</p>