Thread: Really basic string traversal

  1. #1
    Registered User
    Join Date
    Nov 2004

    Exclamation Really basic string traversal


    I seem to have forgotten how to traverse a string of unknown size using a char pointer.


    char *argv[MAX_TOKENS];

    What I thought I should do is make a char pointer
    char *ptr;
    ptr = argv;
    while (ptr){ do something; ptr++; }
    but this will not advance the pointer. What did I forget?

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    I wouldn't name it argv because that's generally used as the name of one of the parameters to main(), but it's legal, so it's up to you.

    Unless your array has a NULL pointer at the end, then your idea of traversing through the array that way is a bad one. You need some way to determine the end, so either it's NULL terminated, or you keep track of the length of the array, or you have some other means of knowing the length.

  3. #3
    Registered User
    Join Date
    Nov 2004
    Rest of the code

    argv[i++] = strtok(cmd, " \t\n");
       while (i < MAX_TOKENS && (argv[i++] = strtok(NULL, " \t\n")) != NULL);

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    If you want to pass argv[] as a parameter to execv() or something similar, or indeed even if you just want to be able to traverse the array with a pointer, set a NULL pointer at the end as MacGyver suggested.
    argv[i++] = strtok(cmd, " \t\n");
       while (i < MAX_TOKENS-1 && (argv[i++] = strtok(NULL, " \t\n")) != NULL);
       argv[i] = NULL;
    Then you could use something like this.
    char *ptr = argv[0];
    while(ptr) {
        ptr ++;

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell

    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ:

    My website:
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problems with overloaded '+' again
    By Brain Cell in forum C++ Programming
    Replies: 9
    Last Post: 04-14-2005, 05:13 PM
  2. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  3. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM