0

Is there a simple and elegant way to split an array from an index?

In my program I am getting a array of strings (argv), and I want to ignore the program name and some of its arguments, copying the rest in an array.

For example, the content of argv is {"program_name", "-o", "file1", "file2"}

I want to retrieve "file1" and "file2" in an array just to make an easy iteration over it.

 // PSEUDO
 char *files[argc - 2] = argv.split(2, argc - 2)

Any ideas?

7
  • 1
    Hmm, argv is not usually a vector. Please make a minimal reproducible example Commented Oct 11, 2020 at 18:17
  • 3
    why don't you just loop over argv starting from the desired index Commented Oct 11, 2020 at 18:18
  • @cigien he probably just meant "array" and used the wrong word. Anyway, there really isn't a better way other than iterating with a loop. You could also just make a loop from i=2 to i<argc, there is no need to copy. Commented Oct 11, 2020 at 18:18
  • In my code, if no files given, I will have to work with a default. Just to make something generalized. Commented Oct 11, 2020 at 18:19
  • C or C++? The answers for each are quite different, please only tag one of the languages Commented Oct 11, 2020 at 18:19

1 Answer 1

3

You can use pointer arithmetic to make it in an elegant way:

char** filenames = argv + 2;

Just be sure that you have at least 2 arguments before your filenames as you wish.

#include <stdio.h>

int main(int argc, char** argv) {
  if(argc > 2){
      //char** that points to the first filename
      char** filenames = argv + 2;
      //number of filenames available to iterate
      int num_of_filenames = argc - 2;

      //Printing each name
      int i = 0;
      for(i = 0; i < num_of_filenames; i++){
        printf("%s\n",filenames[i]);
      }
    }
  return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.