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.
- The condition
*psays “travel onpas long as it’s notNULL, i.e until you have reached the end of the string? - In each iteration
ssums the subtraction of the currentp, the rest of the word, with the name ofargv[i], what is the result of this subtraction? Is this the subtraction of the two ascii values? - What does this program basically do?
The key to answering this question is to understand the meaning of this expression:
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
pis 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 thenargv[i]is subtracted. The result is the length of the corresponding argument.