0

I am trying to duplicate the second commandline argument passed to my program into another string. My goal is to run the program like this:

./a.out param1 word param3 param4

And get a duplicate of word. How do I do that?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93

1 Answers1

2

The first argument is usually name of the executable. So index of the second element you pass in the commandline is 2. Here is how you can do what you're trying to do:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[]) {
  if (argc < 3) {
    puts("Too few arguments");
    return EXIT_FAILURE;
  }

  char* second_arg = strdup(argv[2]);
  printf("Second argument is %s\n", second_arg);
  free(second_arg);
}

If we were duplicating into a fixed string on the stack we would rather do

char second_arg[32];
snprintf(second_arg, sizeof(second_arg), "%s", argv[2]);

but most of the time we want stretchy strings rather than fixed maximum strings so strdup is much preferred.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93