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?

  1. AA and D
  2. BB and C
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. Which of the following is the output when the program above, which uses an array of function pointers, is executed?
  2. fill and use are functions defined elsewhere. Which of the following is a problem with the function above?
  3. Which of the following is true about the pointer returned by the function make above?
  4. In C, which of the following is the most appropriate reason it is recommended to write p = NULL; right after free(p);?
  5. The 8-character string "ABCDEFGH" was passed to the function save above. Which of the following is what happens?