logo

UTK Notes


Clicker Questions - 09-Pointers

The following is the state of memory at address 0x61626324 through 0x6162637f. In each line, I show:

  • The pointer address to the first of four bytes.
  • The four bytes in decimal.
  • The four bytes in hexadecimal.
  • The four bytes in chars.

The machine is little endian, but I’ve printed the characters in big-endian (e.g. 0, 1,2, 3). The pointers are four bytes.

Table.jpg

When you run the following procedure, the value of p is 0x61626324.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
typedef struct ms {
    char a, b, c, d;
    int e;
    char *f;
    struct ms *g;
} Mystruct;

void pm(Mystruct *p) {
    Mystruct *q;

    printf("%c\n", p->b);
    printf("%c%c%c%c\n", p->f[0], p->f[1], p->f[2], p->f[3]);
    printf("%d\n", p[1]->e);
    q = p+4;
    printf("0x%x\n", (unsigned int) q->f);
    q = p->g;
    printf("%c\n", (unsigned int) q->a);
    q = q[1].g;
    printf("%c\n", (unsigned int) q->a);
}
Hint #1 Your first question should be, "How many bytes are in a Mystruct?
Hint #2 Your second question should be, "If I have a pointer to Mystruct, then where do I find the various fields, a, b, c, etc.?"
Hint #3 Your third question should be, "If I have a pointer p, to a Mystruct, then what is the pointer value of p+x?"
Hint #4 (Not Given) The Mystruct struct has 16 bytes:
  • Bytes 0 through 3: the characters a through b.
  • Bytes 4 through 7: the integer e.
  • Bytes 8 through 11: the (char *) f.
  • Bytes 12 through 15: the (Mystruct *)g

Question 1: What is the first line of output?

Answer Since p is 0x61626324, then p->b is the second of the four characters that start at the line. It is the character 'c'.

Question 2: What is the second line of output?

Answer Since p is 0x61626324, then p->f is the pointer stored at 0x6162632c, whose value is 0x61626336. The four characters will be the ones that start at that address, so the output is 'b', 'a', 'k', and 'c'.

Question 3: What is the third line of output?

Answer Since p is 0x61626324 and the Mystruct is 16 bytes, p+1 will be 0x61626334. Therefore, p[1].e will be the four bytes at address 0x61626338: 1633837931.

Question 4: What is the fourth line of output?

Answer Since p is 0x61626324 and the Mystruct is 16 bytes, p+4 will be 0x61626364. Therefore, q->f will be the four bytes at address 0x6162636c: 0x6162633b.

Question 5: What is the fiveth line of output?

Answer Since p is 0x61626324, we know that p->q is the pointer at address 0x61626330, which has the value 0x6162635c. So, q is 0x6162635c. So, q 0x6162635c, and q->a is the first character there: 'v'.

Question 6: What is the sixth line of output?

Answer q is 0x6162635c, so q+1 is 0x6162636c.That means q[1].g is the four bytes 0x61626378 which happen to also equal 0x61626378. When we set q to 0x61626378, q->a is the first character there: 'x'.
Program Output
c
bakc
1633837931
0x6162633b
v
x

PDF Download, 2022 Class Stats, 2023 Class Stats, 2024 Class Stats