C 编程 : Try to compile main class on terminal but it return me ./mainT

标签 c gcc

我正在尝试从命令行参数进行输入。这是我在 c 中的代码

int main(int argc,  char * argv[]) {

    int i;
    if (argc == 0)
    {
        printf("ERROR: You need an argument.\n");
        // We are out of here!
        return 1;
    }

    for( i = 0; i < argc; i += 1 )
    {
        char *pos = argv[0]; // pos is the pointer to the first position
        int possize = sizeof(argv[0]);
        for(i=0;i<possize;i++)
        {
            printf("%c",pos[i]);
        }

        printf("\n");
    }
    return 0;
}

当我尝试从终端运行它时。我输入 gcc main.c-o main,然后输入 ./main,它给了我 ./mainT。为什么这样做?谁能帮我解决这个问题,谢谢。

最佳答案

您需要修正两个错误:

  • argv[0] 不是第一个参数,它是您的程序的名称。如果要打印初始命令行参数,请改用 argv[i],并确保从 1 开始 i
  • sizeof(argv[1]) 不会产生参数的长度;请改用 strlen

关于C 编程 : Try to compile main class on terminal but it return me ./mainT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49590910/

相关文章:

c - C 中的循环展开

c - 如何使用 C 将动态字符串放入数组中

c - 用 C 打开 LDAP 客户端 - 如何替换已弃用的 API

c++ - 将 SWIG 包装器与其他库链接

c - 编写一个程序来找出一系列数字中最大的一个。

c - sizeof 运算符为 (char + short ) 返回 4

c - Keyboard.print() 等同于 C on Teensy?

gcc - Makefile 想自己编译

c - 从 void* 到 char** 的无效转换

c - 解析文件时的 fscanf 格式字符串