Thread: parsing char array

  1. #1
    Registered User
    Join Date
    Dec 2008
    Posts
    4

    parsing char array

    hello,

    I have a char array I would like to parse though but I'm getting hung up. can anyone help? Thanks in advance.

    Code:
    
    char * commands [2] = {"open", "close"};
    
    char **i = commands;
    
    while(*i){
    printf("%s\n",*i);
    i++;
    }
    Basically I think I'm reading past the end of the char array but not 100% sure how to correct.

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    Your loop condition requires that the last string pointer in the array be a 0.
    Code:
        char *commands[] = {"open", "close", 0};
        char **i = commands;
        for (; *i; ++i)
            printf("%s\n", *i);
    Your end-of-array indicator could also be an empty string - which would require one more dereference in the loop condition:
    Code:
        char *commands[] = {"open", "close", ""};
        char **i = commands;
        for (; **i; ++i)
            printf("%s\n", *i);
    Or you could just count the number of elements in the array and index directly:
    Code:
        char *commands[] = {"open", "close"};
        size_t cmd_sz = sizeof(commands) / sizeof(*commands);
        size_t n;
        for (n = 0; n < cmd_sz; ++n)
            printf("%s\n", commands[n]);
    gg

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. newbie needs help with code
    By compudude86 in forum C Programming
    Replies: 6
    Last Post: 07-23-2006, 08:54 PM
  3. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  5. Passing structures... I can't get it right.
    By j0hnb in forum C Programming
    Replies: 6
    Last Post: 01-26-2003, 11:55 AM