This is an awesome problem for a C exam. It requires you to really think about how memory is managed in C.
Let's take it a few parts at a time.
This simply creates an uninitialized int pointer. Most modern compilers represent
int with 32-bits (4-bytes). However, this this very compiler specific. It could easily be represented with only 2 bytes as well. This is a minor problem with the example and for the rest of the time, let's just assume that
an integer is represented with 4 bytes.
static struct {
char a;
char b;
char c;
char d;
} jim = {0,0,0,0};
- static struct {
- char a;
- char b;
- char c;
- char d;
- } jim = {0,0,0,0};
This declares a struct consisting of four char member variables. Since a char is one byte in memory,
the total size of the struct is 4 bytes. A variable
jim is declared with this struct and initialized such that all four char's have value 0.
This simply sets two values in the struct. Our struct in memory now looks like this:
and in
hexidecimal, it looks like this:
Now, since an int is really just 4 bytes strung together, we can cast the struct variable as an integer consisting of those four individual bytes. By casting the first member of the struct to an int pointer and pointing fred at it, you're saying that there is an integer at this location in memory who's first byte is located at fred.a. With me so far?
Now, when we go to access *fred as a regular integer, we're using those bytes as the integer.
But here's the catch: depending on what machine architecture you're working on, it will print something completely different. If you're on an Intel (x86) machine, integers are represented in little-endian byte order, meaning the most significant byte of the integer comes last. On SPARC machines and a few other architectures, integers are represented in big-endian byte order, meaning the most significant byte comes first.
I'm going to assume you're working on an Intel, and so the machine sees your integer as this:
which, in decimal, is 33619968.
On a SPARC machine, it would see your integer as this:
which, in decimal, is 258.
Since you're using the %x specifier in printf(), it will spit out the integer in it's hex form, thus 0x02010000.