0
/* test1.c */
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int m = 11;
    system("./test2 m");
    return 0;
}

上面的程序打印 0,而我希望它打印 11。

/* test2.c */
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int m = atoi(argv[1]);
    printf("%d\n", m);
    return 0;
}

有人可以提供解释吗?还有什么是打印所需的 11 的正确方法?

4

3 回答 3

4

您将字符传递m给命令行,而不是它的值。

于 2013-11-15T11:17:55.847 回答
3

C 不会像 perl 那样扩展字符串常量中的变量,因此m在您的命令中 string 是一个字符串常量。

您需要做的是打印m命令字符串的值:

/* test1.c */
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int m = 11;
    char buf[100];
    sprintf(buf, "./test2 %d", m);
    system(buf);
    return 0;
}
于 2013-11-15T11:19:31.120 回答
3

system() 函数只接受一个字符串作为它的参数。它不知道您有一个名为的变量m,并且它应该替换字符串中的该变量(无论如何在 C 中使用这种语法是不可能的。)

这意味着您正在执行您的第二个程序,如下所示:

 ./test2 m

Your 2 program does atoi(argv[1]); , which will then be the same as atoi("m"); , which makes atoi() return 0.

You need to build up the string you want system() to execute

int main(int argc, char *argv[])
{
    char command[128];
    int m = 11;
    sprintf(command , "./test2 %d", m);
    system(command);
    return 0;
}
于 2013-11-15T11:20:38.433 回答