First of all, the program you posted can't give the stated output. Next time cut-and-paste your program to the message.
your program has
Code:
mystruct.ch[0] = 'A'; // Ascii value 0x41
mystruct.ch[1] = 'B'; // Ascii value 0x42
mystruct.ch[2] = 'C'; // Ascii value 0x43
mystruct.ch[3] = 'D'; // Ascii value 0x44
should be (I'm guessing)
Code:
mystruct.ch[0] = 'A'; // Ascii value 0x41
mystruct.ch[1] = 'B'; // Ascii value 0x42
mystruct.ch[2] = 'C'; // Ascii value 0x43
mystruct.ch[3] = 'D'; // Ascii value 0x44
Now, as to what's happening:
When a struct is used as an argument to a function, the entire struct is pushed on to the stack.
If you want to see how the elements are stored, put the following in your program:
Code:
char *chpoint;
int *intpoint;
int num_ints;
int i;
...
chpoint = (char *)&mystruct;
intpoint = (int *)&mystruct;
num_ints = sizeof(mystruct)/sizeof(int);
printf("sizeof(mystruct) = %d\n", sizeof(mystruct));
for (i = 0; i < sizeof(mystruct); i++) {
printf("0x%08x 0x%02x\n", &chpoint[i], chpoint[i]);
}
printf("\n");
for (i = 0; i < num_ints; i++) {
printf ("0x%08x 0x%08x\n", &intpoint[i], intpoint[i]);
}
printf("\n");
Now in this case, the elements of struct are packed into two ints
The first int contains the bytes 0x41, 0x42, 0x43, and 0x44 (in that order).
The second int contains the value of mystruct.i (decimal 97, the value of the ascii char 'a'.
Now, when mystruct is pushed on the stack, apparently the two ints are pushed in reverse order so that the top of the stack in printf is the int containing the four chars.
Your printf for type1 tells the printf to get an int off of the stack and print its value in hex, so you get 0x44434241 (it thinks it is an int, and this is how ints are stored in little-endian fashion).
Your printf for type 2 tells printf to print a char. Now, chars are always passed as int, so printf gets an int off of stack: (the first four butes of the struct), and print the char value (the least significant byte of the int is 0x41).
Ttttttthat's all folks (unless you want to try some things and tell us something different).
Dave