Frage

$ echo x y z

If you do this, you get

argv[0] = echo
argv[1] = x
argv[2] = y
argv[3] = z

I want to know this principle.

I want to make the program with following conditions.

  • input: string (type: char *)

    char * str = "echo x y z";  
    
  • output: strings (type: char **)

Print

argv[0] = echo
argv[1] = x
argv[2] = y
argv[3] = z

The memories in this program should be made dynamically (NOT knowing string size in advance)

War es hilfreich?

Lösung

You can initialize the output with a default capacity, then when need, you can reallocate the memory as need

Some thing like

char** parse(char* input) {

    char* str = strdup(input);
    int count = 0;
    int capacity = 10;

    char** result = malloc(capacity * sizeof(char*));
    char* tok = strtok(str," "); 

    while(tok != NULL){
        if (count >= capacity) {
            capcity = 2 * capacity; // or grow it the way as you need
            result = realloc(result, capacity * sizeof(char*));
        }
        result[count++] = strdup(tok);

        tok=strtok(NULL," ");
    } 

    free(str);
    return result;
}

Just the idea, hope it helps

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top