简体   繁体   English

main和main()之间的区别

[英]Difference between main and main()

The following code 1 is fine 以下代码1很好

#include <stdio.h>    // code 1
main()
{
    printf("%u",main);
}

but this code 2 gives segmentation fault. 但是此代码2给出了分段错误。

#include <stdio.h>  // code 2
main()
{
    printf("%u",main());
}

I'm not getting what's the difference between main and main()? 我没有得到main和main()有什么区别?

Did you compile with all warnings enabled from your compiler? 您是否已使用编译器启用的所有警告进行编译? With gcc that means giving the -Wall argument to gcc (and -g is useful for debugging info). 使用gcc意味着将-Wall参数赋予gcc (而-g对于调试信息很有用)。

First, your printf("%u", main) should be printf("%p\\n", main) . 首先,您的printf("%u", main)应该是printf("%p\\n", main) The %p prints a pointer (technically function pointers are not data pointers as needed for %p , practically they often have the same size and similar representation), and you should end your format strings with newline \\n . %p输出一个指针(技术上函数指针不是%p所需要的数据指针,实际上它们通常具有相同的大小和相似的表示形式),并且您应该使用换行符\\n结束格式字符串。 This takes the address of the main function and passes that address to printf . 这将获取main函数的地址 ,并将该地址传递给printf

Then, your second printf("%u", main()) is calling printf with an argument obtained by a recursive call to the main function. 然后,您的第二个printf("%u", main())调用printf并带有通过递归调用 main函数获得的参数。 This recursion never ends, and you blow up your call stack (ie have a stack overflow), so get a SIGSEGV on Unix. 这种递归永远不会结束,您会炸毁调用堆栈(即,堆栈溢出),因此在Unix上获得SIGSEGV

Pedantically, main is a very special name for C standard, and you probably should not call it (it is called auto-magically by startup code in crt0.o ). 在学上, mainC标准的一个非常特殊的名称,您可能不应该调用它( crt0.o的启动代码会自动对其进行魔术调用)。 Recursing on main is very bad taste and may be illegal. main上进行递归非常不好,可能是非法的。

See also my other answer here . 另请参阅我的其他的答案在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM