C Programming Basics
char s[] = "abc", t[] = "xyz";
const char *p = s;
char *const q = s;After the declarations above, one of the statements A "p = t;", B "*p = 'x';", C "q = t;" or D "*q = 'x';" is written. Which of the following is the combination that causes compile errors?
- AA and D
- BB and C
- CB and D
Show answer and explanation
Answer: B. B and C
const char *p is a "pointer to const char": the character it points to cannot be modified through p, but p itself can be changed to another address. char *const q is a "const pointer": q cannot be changed, but what q points to can be modified. So B (assigning to *p) and C (assigning to q) cause errors. Read it as: const to the left of * fixes what is pointed to, and const to the right fixes the pointer itself.
- A. A changes p itself and D changes what q points to; both are allowed.
- B. Correct. Changing what p points to, and changing q itself, cause errors.
- C. D, *q = 'x';, assigns to a non-const char, so it can be modified.