为什么这个 final.exe 文件会无限循环执行,而不是如下指定的数字?

Why does this final.exe file execute in an infinite loop instead of the specified number as below?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[]) 
{
   int i; 
    if (argc < 2)
    {
        printf("ERROR: You need at least one argument.\n");
        return 1;
    } 
   else 
   {
        int i, j;
          
           for(i=1;i<=(int)*argv[1];i++)
            {
                printf("\n");
                (void)system("test1.exe");
            }
    } 
}

test.c 文件包含:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() 
{
  printf("Hello World");
}

(int)*argv[1]是以第一个字符的字符编码作为迭代次数。字符编码通常与字符代表的数字不同。

要将字符串转换为相应的数字,可以使用atoi()(如果您不关心无效输入)。

        int i, j;
        int num = atoi(argv[1]);
          
           for(i=1;i<=num;i++)
            {
                printf("\n");
                (void)system("test1.exe");
            }

for(i=1;i<=(int)*argv[1];i++)

表达式(int)*argv[1]使用第一个命令行参数(不包括程序名)的第一个字符作为数字。也就是说,假设使用类 ASCII 或类 Unicode 编码,字符 0 被视为值 48,1 被视为 49,...,而 9 被视为 57。 (int) 并没有什么不同。

如果你真的只想使用第一个字符,你可以这样做

if (isdigit(*argv[1])) {
    int count = *argv[1] - '0'; // works with any encoding

或者要允许多位数计数,您可以这样做

char *parse_end;
int count = strtol(argv[1], &parse_end, 10);
if (parse_end != argv[1] && *parse_end == '[=11=]' && count >= 0) {