简体   繁体   中英

C - How to copy part of an array of string into another?

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM