strtok question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • schmals
    New Member
    • Oct 2007
    • 8

    strtok question

    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:

    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]);
    	}
    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!
  • gpraghuram
    Recognized Expert Top Contributor
    • Mar 2007
    • 1275

    #2
    Hi,
    Since you have done a strtok the ip string wont have anything or only the first part of the string.(That is to get number of tokens)
    You are doing strtok again to get the individual strings.
    Since the source string is empty strtok is not working.
    What i suggest is to get the number of tokens iterate through the string to find number of spaces.
    Or after the first strtok reinitialize the input again.

    Raghuram

    Comment

    Working...