简体   繁体   中英

How to correctly store array of strings into array (In C)?

*Edited*

Essentially, in a program I am writing I have initialised the following:

char **cmd[16];
cmd[15] = '\0';

I then loop through an piped in text file which contains lines of text. For example, when executing the program I will run./a.out < file.txt

Within this loop, I break each line of the file into strings and store them in char *arguments[] .

For example, the line of text "ls -n 5" creates arguments = {"ls", "-n", "5", NULL}

I then assign the pointer to arguments to an index of cmd based on the line number. Ie, cmd[line_number] = arguments;

My problem arises when I exit the while loop. Every index of cmd now points to the exact same thing, since what arguments points to has been changed. So even if I have a text file with:

ls -s1
sort -n
ls -n 5

cmd will contain 3 arguments, which all have the last line {"ls", "-n", "5", NULL}

My question is whether there's a way I can assign the current value of arguments to cmd[line_number], without the value inside being overridden in the next iteration.

The following is the relevant code:

int main(int argc, char **argv) {

    char ** cmd[16];
    cmd[15] = '\0';

    char buffer[256];

    int number_of_lines = 0;

    // Initialise arguments
    char * arguments[256];

    // Read until EOF
    while (fgets(buffer, sizeof(buffer), stdin) != NULL) {

        // tokenise buffer into arguments
        // E.g. "Hello World" => arguments = {"Hello", "World", NULL}
        parsecmd(buffer, arguments);

        // Points to arguments
        cmd[number_of_lines] = arguments;

        number_of_lines++;
    }
    return 0;
}

Here is the parsecmd function as well:

void parsecmd(char *buffer, char **arguments) {

    // Get Pointer to \n in string
    char *newline = strchr(buffer, '\n');
    // Remove if found
    if (newline) {
        *newline = 0;
    }

    int i = 0;
    int token_count = 1;    
    // token equal to first to first string before whitespace in buffer
    char * token = strtok(buffer, " ");

    // While tokens remain
    while (token != NULL) {
        // Store token in arguments
        arguments[i] = token;

        // Get next token
        token = strtok(NULL, " ");

        // Increment counters
        i++;
        token_count++;
    } 

    // Assign all unnasigned variables to NULL 
    for (i = token_count - 1; i < 256; i++) {
        arguments[i] = NULL;
    }
}

Any help or suggestions would be much appreciated:)

suggest replacing:

printf("%s\n", cmd[0][0]);

with:

printf("%s\n", args[0]);

because the output format specifier: %s is expecting a pointer to the string, not the first char of the string

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