Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this program basically do? Subtraction of pointers?

Tags:

c

string

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.

  1. The condition *p says "travel on p as long as it's not NULL, i.e until you have reached the end of the string?
  2. In each iteration 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?
  3. What does this program basically do?
like image 465
Numerator Avatar asked Feb 14 '26 02:02

Numerator


1 Answers

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.

like image 60
Sergey Kalinichenko Avatar answered Feb 16 '26 17:02

Sergey Kalinichenko