Answers/Solutions to Exercises in Chapter 3, Exercise 6
E6: In a C program, we store two short integers in an int variable and retrieve them and display them later in the
program:
short* p;
int x;
...
p = (short*) &x;
*p++ = 1;
*p = 2;
...
p =
(short*) &x;
// this statement was missing in the book
printf("first short=%d,second short=%d\n",*p, *(p+1));
During the execution we will see on the screen first
short=1,second short=2. What will we see if we compile and execute our program on a
machine that has the opposite ``endianess"?
A6: Of course, if the program was as printed in the book, it would not display the
message first short=1,second short=2 as the pointer (p+1)
points outside of where we stored the two short integers. So we corrected the program and
after storing the two shorts in x, we re-point p to the
beginning of x again. Now it performs correctly, and we
can return to the original question.
The answer is -- no difference, we will see the same message. The fact that we are
storing the values in x is coincidental, not essential to anything. We just store two
shorts somewhere in memory and read them back. Of course, the storing and the reading is
done according to the endianess, but it does not have any effect on the result.
Back to Answers/Solutions Index Back to Answers/Solutions for Chapter 3 Index