Reputation: 1465
What is the output of the following program, if we pass to it the following parameters through the command line:
bcd abcd ab abc
So, since we pass 4 arguments, argc
is 4?
We initialize i to 2 and then go and checked argv
's from 1 to 3 - my guess would be we add i = 2, and later, in the next iteration i = 3, and that's 5, so the output would be 5?
void main(int argc, char* argv[])
{
char *p, *q;
int i = 2, j = 0, k = 0;
for (; i < argc; i++)
{
p = argv[i-1];
q = argv[i];
for (j = 0; *q && *p; j++, p++, q++)
{
if (*p != *q)
{
break;
}
}
if (!*p || !*q)
{
k += i;
}
}
printf("%d",k);
}
Upvotes: 0
Views: 200
Reputation: 2857
Can you explain why is argc 5, and not 4? and what would be argv[0]?
The argv[0]
is you program's name. like a.out
or something else you named. argv[1] ...
is the params you passed to the program. so argc
is 1+ paramNumberYouPassed.
Upvotes: 0
Reputation: 22905
argc
is 5.
This program checks each pair of consecutive arguments and counts how many are substrings of each other (either the first is a substring of the second or vice versa):
bcd abcd // i = 2
abcd ab // i = 3, good
ab abc // i = 4, good
In this case, since i=3
and i=4
fit the criteria, k
is 7.
Breaking down the code, the innermost for loop exits if there is a different character or if one string ends. The line if (!*p || !*q) k += i;
increases k
only if one of the strings hit the end.
Upvotes: 1