Hi,
I am writing a UNIX shell program and have encountered a problem that I have spent way too many hours trying to solve to no avail. I have narrowed down my problem concisely and made a easier to follow test program that has the same problem in it. Here is the code for the sample program:
The problem happens when I get to the for loop that should populate sargv[] with the arguments (hello, my, name, is, Scott). It get the first argument because it's outside of the loop, but when it goes back to get the second argument (in word), it must be set to NULL instead of the argument and exits the loop. Why isn't strtok working for me here like it should?! Any help would be very, very appreciated!
I am writing a UNIX shell program and have encountered a problem that I have spent way too many hours trying to solve to no avail. I have narrowed down my problem concisely and made a easier to follow test program that has the same problem in it. Here is the code for the sample program:
Code:
char string[] = "hello my name is Scott";
char* word;
char** sargv;
int arg_count = 0;
int i;
/* get argument count */
word = strtok(string, " ");
while (word != NULL) {
word = strtok(NULL, " ");
arg_count++;
}
/* allocate memory in heap for array of strings */
arg_count++; /* increment arg_count so that sargv will be null-terminating */
sargv = calloc(arg_count, sizeof(char*));
word = strtok(string, " "); /* get first word implicitly */
sargv[0] = malloc(strlen(word)*sizeof(char) + 1); /* allocate memory to hold it */
strcpy(sargv[0], word); /* add it to sargv */
/* iterate through all arguments and add them to sargv */
for (i = 1; word != NULL; i++) {
printf("loop\n");
word = strtok(NULL, " ");
if (word != NULL) {
sargv[i] = malloc(strlen(word) * sizeof(char) + 1);
strcpy(sargv[0], word);
}
}
/* print values of sargv */
for (i = 0; sargv[i] != NULL; i++) {
printf("sargv[%i]: %s\n", i, sargv[i]);
}
Comment