int main(int argc, char* argv[])
{
int i,s;
s=0;
char*p;
for(i=1; i<argc;i++)
{
for (p=argv[i];*p;p++);
s+=(p-argv[i]);
}
printf("%d\n",s);
return 0;
}
I'm having a hard time understanding what does this code does.
As far I see it, it ignores the program's name and for every other string which was printed in the command line it sets p to be the current string.
*p says "travel on p as long as it's not NULL, i.e until you have reached the end of the string? s sums the subtraction of the current p, the rest of the word, with the name of argv[i], what is the result of this subtraction? Is this the subtraction of the two ascii values?The key to answering this question is to understand the meaning of this expression:
p-argv[i]
This is a pointer subtraction expression, which is defined as the distance in sizes of elements pointed to by the pointer between the first and the second pointer. This works when both pointers are pointing to a memory region that has been allocated as a contiguous block (which is true about all C strings in general and the elements of argv[] in particular).
The pointer p is first advanced to the end of the string (note the semicolon ; at the end of the loop, which means that the loop body is empty), and then argv[i] is subtracted. The result is the length of the corresponding argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With