Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

If you define your main with the signature as

int main(int argc, char *argv[]);

then, here argv is an array of pointers to strings passed as command line arguments. Quoting the C99 standard section 5.1.2.2.1 -

The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.

Therefore, you can either directly modify the strings pointed to by elements of argv, or you can copy those strings and then process them.

#include <stdlib.h>

int main(int argc, char *argv[]) {
    char *strlist[argc];
    int i = 0;
    while(i < argc) {
        strlist[i] = malloc(1 + strlen(argv[i]));
        if(strlist[i] == NULL) {
            printf("not enough memory to allocate\n");
            // handle it
        }
        strcpy(strlist[i], argv[i]);
        i++;
    }
    // process strlist
    // after you are done with it, free it
    for(i = 0; i < argc; i++) {
        free(strlist[i]);
        strlist[i] = NULL;
    }

    return 0;    
}

argv is a 'string array' itself: it is an array of char*.

You can simply duplicate it (allocating memory for each element). Using a 2D array of char (as you suggest) for strings might be not a very efficient approach.

This depends on what you want to achieve.

  • You can use argv as it is. argv is already an array of string pointers.
  • You can use a fixed size array, e.g. char argv_copy[7][256]. This means, you can use an array, which is large enough for the expected strings
  • As you suggested, you can go through argv and look for the largest string.
  • You can simply copy the argv structure, which means

    char **argv_copy = malloc((argc - 1) * sizeof(char*));
    int i;
    for (i = 1; i < argc; ++i) {
        argv_copy[i - 1] = malloc(strlen(argv[i]) + 1);
        strcpy(argv_copy[i - 1], argv[i]);
    }
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top