我不小心让argc和argv在main函数之外工作.

以下是重现此"错误"的代码(与GCC一起编译):

手C

#include <stdio.h>

int test(void);

int main(void)
{
    test();
}

Test.c

#include <stdio.h>

int test(int argc, char **argv)
{
    printf("argc = %i\n", argc);
    printf("args:\n");
    for (int i = 0; i < argc; i++)
    {
        printf("- %s\n", argv[i]);
    }
    printf("test called\n");
    return 0;
}

推荐答案

As comments already hinted, it is not so much a case of
"I accidentally made argc and argv work",
but more of
"I made argc and argv work accidentally".

I.e. you did not stumble across something which works reliable,
instead your code only accidentally works in no reliable way.

The concept of "undefined behaviour" is an important one in C.
It pays to make yourself familiar with it. That can even be fun, e.g. read up on "nasal demons".
Most relevant for your case is that UB can, among other things, fiendishly deceive you into believing that your program works; I consider this to actually be the worst case of possible outcomes.

正如pmacfarlane在 comments 中给出的原因,你最终会有不确定的行为:

您得到了未定义的行为,因为您使用错误的参数数量和类型调用了test().

C++相关问答推荐

intellisense不工作,甚至已经下载了c/c++扩展

球体—立方体重叠:无、部分或全部?

C中的__attributor__((aligned(4),packed))与 struct 的用法

在C中使用动态内存分配找到最小的负数

C中是否有语法可以直接初始化一个常量文本常量数组的 struct 成员?

当多个线程在C中写入相同的文件描述符时,如何防止争用情况?

以前版本的tty_ldisc_ops.ioctl()是否也需要文件参数?

从纯C中访问通用项对话框

为什么GDB/MI进程的FIFO循环中有read()阻塞

C中函数类型的前向声明

struct -未知大小

&;(str[i])和(&;str)[i]有什么区别?

如何读取文件并将内容保存在字符串中?(在C语言中,没有崩溃或核心转储错误)

为什么电路板被循环删除?

安全倒计时循环

将非连续物理内存映射到用户空间

C中的数组下标和指针算法给出了不同的结果

gdb - 你能找到持有内部 glibc 锁的线程吗?

strlen 可以是[[未排序]]吗?

我们可以在不违反标准的情况下向标准函数声明添加属性吗?