LearnFrenzy
Sign in Take a free test

Command Line Arguments · Find the Error · Question 5

Error: argv[1] + argv[2] to join two arguments Answer, explanation & discussion

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

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

main.c
#include <stdio.h>

int main(int argc, char *argv[]) {
    if (argc != 3)
        return 1;
    char *joined = argv[1] + argv[2];
    printf("%s\n", joined);
    return 0;
}
  • A joined must be const
  • B printf needs %c
  • C argv[1] and argv[2] are pointers, and C cannot add two pointers; join strings with snprintf() into a buffer Correct
  • D There is no bug
Correct Answer: Option C

C has no string concatenation operator. Allocate or declare a buffer and use snprintf(buf, sizeof buf, "%s%s", argv[1], argv[2]).

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