Numerator
Numerator

Reputation: 1409

What does this program basically do? Subtraction of pointers?

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?

Upvotes: 3

Views: 179

Answers (4)

bigkm
bigkm

Reputation: 2277

Its using pointer addresses in a backwards type way to calculate the total characters in all args.

for (p=argv[i];*p;p++); //sets p to the address of argv[i]'s \0 terminator
   s+=(p-argv[i]);     // p minus the address of the start of argv[i] accumulated to s

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726929

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.

Upvotes: 2

Andy Stow Away
Andy Stow Away

Reputation: 647

It tells you the total string length of all the arguments you passed to the program.

In your point (2), it just subtracts the starting address of the string with the address that holds the \0 character

Upvotes: 1

Oleg Razgulyaev
Oleg Razgulyaev

Reputation: 5935

This code calculates sum of lengths of arguments (as strings) of the program

Upvotes: 1

Related Questions