I found this function and I don’t understand certain parts of it. I have about 3 days worth of C experience, so bear with me. This function serves a purpose of parsing command-line arguments.
-
Why do they reassign
*argto*c? -
I don’t understand why they are running a while loop.
-
Secondly, why would they run a while loop against a char pointer? I understand that a char is actually an array of characters, but my understanding is that they would only run a while loop against a char is to access the array character values individually, and they don’t do any of that.
-
How can you increment against a char?
-
Why do we even have *c?
-
I added the string check to see if the arg is
-stylesfor example, which has a-so I can parse the flag and obtain the value, which is the next arg inargv— is that correctly used?
Like I said, I’ve got about 3 days of C experience, so please be thorough and methodical and as helpful as possible as to help me better understand this function and C overall.
void print_args(int argc,char *argv[])
{
int i;
if(argc > 1){
for(i=1;i<argc;i++){
char *arg = argv[i];
char *c = arg;
while(*c){
if(strchr("-", *c)){
printf("arg %d: %s -> %s\n",i,arg,argv[i+1]);
}
c++;
}
}
}
}
1)
argis assigned to point to the head of the current char array, andcis used to traverse the array.2,3,5) The while loop is run until
cpoints to(char)0, which incidently is also\0. So in effect they go over every character in the char array, until they reach the null terminator symbol. A better conditional would have beenwhile (*c != '\0'), rather than relying implicitly that'\0' == 04) They increment a pointer, Thus having it point to the next memory cell, i.e. the next array cell.
6) Your addition will work as a test to recognise an option, you’d still have to compare it against
-stylesto see that it is indeed a valid option.This code sample could do with a lot of fixing up to make it more robust and clearer.
If this is from a book or C tutorial, I suggest you look for another.