223k views
2 votes
Which one is not legal? char const *string1 = "Go Bucks!";

1. printf("%s",string1);
2. string1 = "Go!..............................";
3. string1[0] = 'C';
4. string1 = "Go!";

1 Answer

5 votes

Final answer:

Option 3, 'string1[0] = 'C';', is not legal because string1 points to a constant character sequence, which cannot be modified.

Step-by-step explanation:

The student has asked which of the following pieces of code is not legal when considering the declaration char const *string1 = "Go Bucks!";

  1. printf("%s",string1);
  2. string1 = "Go!..............................";
  3. string1[0] = 'C';
  4. string1 = "Go!";

The correct answer is 3. string1[0] = 'C';. This is because string1 is a pointer to a constant character sequence. You can change where the pointer string1 points to, as demonstrated in cases 2 and 4, but you cannot change the contents of the string itself, as you would attempt to do in case 3. Attempting to modify a constant character sequence (string literal) is illegal in C and will result in a compile-time error.

User AMother
by
8.1k points