【发布时间】:2021-01-12 11:43:04
【问题描述】:
这是一本书的示例代码。该程序打印给定的字符串以重复给定的次数。
#include <stdio.h>
#include <stdlib.h>
void usage(char *program_name)
{
printf("Usage: %s <nessage> <# of times to repeat>\n", program_name);
exit(1);
}
int main(int argc, char *argv[]) {
int i, count;
if(argc < 3)
usage(argv[0]);
count = atoi(argv[2]);
printf("Repeating %d times..\n", count);
for(i=0; i < count; i++)
printf("%3d - %s\n", i, argv[1]);
}
它做了它应该做的:
kingvon@KingVon:~/Desktop/asm$ ./convert 'Stackoverflow is the best place to ask questions about programming' 6
Repeating 6 times..
0 - Stackoverflow is the best place to ask questions about programming
1 - Stackoverflow is the best place to ask questions about programming
2 - Stackoverflow is the best place to ask questions about programming
3 - Stackoverflow is the best place to ask questions about programming
4 - Stackoverflow is the best place to ask questions about programming
5 - Stackoverflow is the best place to ask questions about programming
kingvon@KingVon:~/Desktop/asm$
问。现在虽然main 以这个特定的顺序接受两个参数:(int argc, char *argv[]),但为什么当我./convert 'string' (number) 时它可以正常工作,但 `./convert (number) 'string' 的其他方式不起作用?
kingvon@KingVon:~/Desktop/asm$ ./convert 5 'Stackoverflow is the best place to ask questions about programming'
Repeating 0 times..
问。这条线
if(argc < 3) usage(argv[0]);
我有 2 个问题: 此行指定如果给定的整数参数小于 3,则程序应输出用法。 ./convert 'string' 2 不打印用法?那么这里发生了什么?同样usage 将char *program_name 作为参数(char *program_name 是什么意思?)但在上面的行中给出了argv[0] 作为参数。为什么会这样?这样做有什么作用?
【问题讨论】:
-
当你做
./convert 'Stackoverflow is the best place to ask questions about programming' 6时,argc不是6。 -
为什么投反对票?