Search code examples
ccommand-line-argumentsdynamic-arraysargvc-strings

In C how do I dynamically add command line arguments to a string array?


At the moment the only way I can see it is by cycling through the argv argument list, getting the largest of the input strings and creating a new dynamic array with this largest size dictating the memory allocation for each element.

Or is there a more straightforward way?


Solution

  • See if the following helps:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(int argc, char* argv[]) {
      char** myStrings;
      int ii;
      myStrings = malloc(argc * sizeof *myStrings);
      for(ii = 0; ii < argc; ii++) {
        myStrings[ii] = malloc(strlen(argv[ii])+1);
        strcpy(myStrings[ii], argv[ii]);
      }
      for (ii = 0; ii < argc; ii++) {
        printf("copied argument %d: it is '%s'\n", ii, myStrings[ii]);
      }
    }