[英]Explain the output of this program?
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? 因此,由于我们传递了4个参数,因此argc
为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? 我们将i初始化为2,然后检查argv
从1到3-我的猜测是我们将i = 2,然后在下一次迭代中i = 3,即5,所以输出为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);
}
argc
is 5. argc
是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. 在这种情况下,由于i=3
和i=4
符合条件,因此k
为7。
Breaking down the code, the innermost for loop exits if there is a different character or if one string ends. 分解代码,如果有另一个字符或一个字符串结束,则最里面的for循环退出。 The line if (!*p || !*q) k += i;
该行if (!*p || !*q) k += i;
increases k
only if one of the strings hit the end. 仅当其中一个字符串结束时才增加k
。
Can you explain why is argc 5, and not 4? and what would be argv[0]?
The argv[0]
is you program's name. argv[0]
是您的程序名称。 like a.out
or something else you named. 例如a.out
或您命名的其他名称。 argv[1] ...
is the params you passed to the program. argv[1] ...
是您传递给程序的参数。 so argc
is 1+ paramNumberYouPassed.
所以argc
是1+ paramNumberYouPassed.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.