LearnFrenzy
Sign in Take a free test

Strings · Find the Error · Question 3

Error: strtok() on a string literal Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

The program below has a problem. Which statement correctly describes it?

main.c
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links