Question 3
Back to Exercise
The program below has a problem. Which statement correctly describes it?
#include <stdio.h>
#include <string.h>
int main(void) {
char *csv = "red,green,blue";
for (char *t = strtok(csv, ","); t != NULL; t = strtok(NULL, ","))
puts(t);
return 0;
}
- A The delimiter must be a char, not a string
- B strtok() writes '\0' into csv, but csv points to a read-only string literal Correct
- C strtok(NULL, ",") is invalid
- D There is no error; it prints the three colours
Correct Answer: Option B
strtok() modifies the string it splits. A string literal may not be modified, and on most systems this crashes. Use a writable copy: char csv[] = "red,green,blue";.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!