G
G
GlowMan2019-02-21 20:16:03
C++ / C#
GlowMan, 2019-02-21 20:16:03

Why is the structure being converted incorrectly?

Why is it that when I convert from struct my_struct_in to struct my_struct and output it, it doesn’t work out as it should, why there aren’t eight 0s and what a garbage value. What is it for? I know it's bullshit, but I just want to get the gist of it.

#include <stdio.h>
#include <string.h>

#define AF_INET 1
#define __STRUCTADDR_COMON(sa_prefix) unsigned short int sa_prefix##family

struct my_struct 
{
  __STRUCTADDR_COMON(sa_);
  char data[14];
};

#define my_structContent_size (sizeof(struct my_struct) - sizeof(unsigned short int) - sizeof(unsigned short int) - sizeof(unsigned int))

struct my_struct_in
{
  __STRUCTADDR_COMON(sa_);
  unsigned short int port;
  unsigned long int addr;
  unsigned char sin_zero[my_structContent_size];
};
//base^exp
int power(int base, unsigned int exp)
{
    int i, result = 1;
    for (i = 0; i < exp; i++)
        result *= base;
    return result;
}

void print_byte(unsigned int *value, int col_byte)
{
  unsigned int byte, mask = 0xff*power(256, col_byte-1), shift =  power(256, col_byte-1), byte_itr, bit_itr;
               //mask *= power(256, col_byte-1);
               //  shift = power(256, col_byte-1);
  for(byte_itr = 0; byte_itr < col_byte; byte_itr++)
    {
      byte = ((*value) & mask) / shift;
      for(bit_itr = 0; bit_itr < 8; bit_itr++)
  {
    if(byte & 0x80)
      printf("1");
    else
      printf("0");
    byte*=2;
  }
      printf(" ");
      shift /= 256;
      mask /=256;
    }
  printf("\n");
}

int main(int argc, char **argv)
{
  struct my_struct_in host_addr;

  host_addr.sa_family = AF_INET;
  host_addr.port = 80;
  host_addr.addr = 1282342;
  memset(&(host_addr.sin_zero), '\0', my_structContent_size);

  struct my_struct *host;
  host = (struct my_struct *)&host_addr;
  unsigned int data;
  for(int i = 0; i < 14; i++)
    {
      data = (host->data[i]);
      print_byte(&data, 1);
    }
  return 0;
}
5c6eddd694e8f702458274.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2019-02-21
@DoYouGot

What is it for?

Because of the alignment of the data fields in the structure, and because long is 8 bytes. In the my_struct_in structure, you have short, short, and long in a row. The first two shorts are aligned, and to align the long, the compiler inserted a 4-byte hole in front of it into the structure. You can print offsetof(struct my_struct_in, addr)to verify this.
What to do? Use fixed-width types ( uint32_t addr, if you meant an IP address). Pack structures (if alignment is not possible), or arrange fields according to their natural alignment.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question