0

I have a simple C program of below type

#include<stdio.h>
struct test{
char a;
char b;
char c;
char d;
int e;
};

void main() {
    struct test mem = {0xa, 0xb, 0xc, 0xd, 0xef12};
    long int *tmp = (long int *)(&mem.a);
    printf("Struct in binary %p : 0x%lx\n", &mem.a, *tmp);
    printf("Printing only a member %p : 0x%x\n", &(mem.e), *(int *)(&(mem.e)));

}

The output of above program is as below on a Big endian machine :

Struct in binary 0x7ffc1206abc0 : 0xef120d0c0b0a

Printing only a member 0x7ffc1206abc4 : 0xef12

The question is that why is the raw output of the struct in the reverse order of its members' values?

The address of 'member e' is still 4 bytes from the start of the struct base address..!

Gerd
  • 2,568
  • 1
  • 7
  • 20
tss
  • 111
  • 1
  • 6
  • I believe you don't understand, that `long int` is big endian in itself. So aliasing the struct with `long int` will print memory content in reverse order. Where does the text `Printing only a member` come from? Could you edit your question and clear the program output, put it inside code formatting? – KamilCuk Dec 30 '19 at 11:02
  • The machine is a big endian machine. Can you please elaborate on what "long int is big endian in itself" mean? – tss Dec 30 '19 at 11:18
  • 1
    Doing `*(long int*)memory` will access the memory in the way `long int` accesses memory - in big endian. To print bytes, alias the memory with `char` and iterate over bytes. – KamilCuk Dec 30 '19 at 11:23
  • Note that `long int *tmp = (long int *)(&mem.a);` and getting a `long int` value via `*tmp` is a [strict-aliasing violation](https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule) and can also result in undefined behavior and program failure should the resulting address not be properly aligned. – Andrew Henle Dec 30 '19 at 11:27
  • Why are you sure that your machine is big endian? I don't think so. I tried your code on a little endian machine and it gives the same output, as I expected. – the busybee Dec 30 '19 at 12:03
  • @thebusybee is right, it looks like you are running on a little-endian system. – jamieguinan Dec 30 '19 at 12:39

0 Answers0