-
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.
-
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