switch case for parsing options
c, pointers
Solution
If you want to iterate through program arguments looking for the terminating null pointer, your outer cycle should be
while (*++argv)
not the
while (++*argv) // <- incorrect!
that you have in your code.
Your `switch` expression is written incorrectly. While your intent is clear, your implementation ignores operator precedence.
This
switch (*argv[1]) { // <- incorrect!
should actually be
switch ((*argv)[1]) {
The previous `if`
if (**argv == '-')
is fine, but since it is equivalent to
if ((*argv)[0] == '-') // <- better
maybe you should rewrite it that way as well, just for consistency with `switch`.
Problem
I am writing a simple program which takes the arguments form the user and process them. I have the arguments in the argv which is two dimensional array. But when i ran the program, i get the garbage value and the segmentation fault error. I have tried with using argc as terminating condition and it works. But i want to do it using the pointer only. What am doing wrong with pointer here. ``` #include<stdio.h> int main( int argc, char *argv[]) { while (++(*argv)) { if ( **argv == '-' ) { switch (*argv[1]) { default: printf("Unknown option -%c\n\n", (*argv)[1]); break; case 'h': printf("\n option h is found"); break; case 'v': printf("option V is found"); break; case 'd': printf("\n option d is found"); break; } } printf("\n outside while : %s", *argv); } } ``` program run as: ``` ./a.out -h -v -d ``` Thank you