C Programming Basics
int is 4 bytes and pointers are 8 bytes. When the value (address) of a pointer to int p is 0x1000, which of the following is the value of p + 3?
- A0x100C
- B0x1012
- C0x1018
Show answer and explanation
Answer: A. 0x100C
Adding an integer to a pointer advances it in units of the size of the pointed-to type. int is 4 bytes, so p + 3 points 3 × 4 = 12 bytes ahead, that is, to 0x1000 + 0xC = 0x100C. p + 3 is the address of the array element p[3], and *(p + 3) means the same as p[3]. A pointer to char advances 1 byte at a time, and a pointer to double (8 bytes) 8 bytes at a time.
- A. Correct. It advances three steps of 4 bytes, so 12 = 0xC is added.
- B. This is the value obtained by adding 12 bytes as "12" without converting to hexadecimal. Decimal 12 is 0xC in hexadecimal.
- C. This is the value obtained by advancing in steps of the pointer's own size (8 bytes) (3 × 8 = 24 = 0x18).