Store tokens in dynamic C array

Asked

Viewed 47 times

0

I am developing a console application that works as a shell (using processes to process commands sent via stdin). Entering the command to process with fgets(command, 1024, stdin) saves the whole command and wanted to split the string into several strings separated by spaces (save the different arguments of the command). When making a while(argument != null) cycle I wanted to save each argument to an auxiliary vector. How do I create a dynamic vector and within the cycle assign the value of the argument to the position n of the vector (in light ascending order)? Below I have the code I’m using for the intended.

    char *command = malloc(MAX_COMMAND_SIZE);
    int arg_counter = 0;

    char **command_args;

    fgets(command, MAX_COMMAND_SIZE, stdin);

    char *command_arg = strtok(command, DELIM);

    while(command_arg != NULL)
    {
        printf("arg %d: %s\n", arg_counter, command_arg);

        strcpy(command_args[arg_counter], command_arg);

        arg_counter++;

        command_arg = strtok(NULL, DELIM);
    }

Notes:

MAX_COMMAND_SIZE = 1024

Thanks for the help

  • 1

    I do not know if I understand correctly your doubt but you have evaluated the use of the function strtok of <string.h>?

  • Yes I can already show each token per line and wanted to store each token in a dynamic array (grows according to the inserted command).

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.