简体   繁体   English

C语言中的main函数可以返回指针吗?

[英]Can the function main in C return a pointer?

As the heading goes, Is it possible for the main function return a pointer? 随着标题的进行,主函数是否可以返回指针? If yes then where would be useful? 如果是,那么在哪里有用? Thanks! 谢谢!

Only a return type of int is blessed by the standard: 标准只接受int的返回类型:

5.1.2.2.1 Program startup 5.1.2.2.1程序启动

1 The function called at program startup is named main. 1在程序启动时调用的函数称为main。 The implementation declares no prototype for this function. 该实现没有为此函数声明任何原型。 It shall be defined with a return type of int and with no parameters: 它应使用返回类型int且不带参数来定义:

 int main(void) { /* ... */ } 

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared): 或带有两个参数(尽管可以使用任何名称,但在此处称为argc和argv,因为它们是声明它们的函数的局部名称):

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

or equivalent;10) or in some other implementation-defined manner. 或等效; 10)或以其他一些实现定义的方式。


C11 draft, April 12, 2011 C11草案,2011年4月12日

Everything else is up to your compiler and therefore not a C-question anymore. 其他一切都取决于您的编译器,因此不再是C问题。

No. main() returns an int in standard C. The interpretation of this return value is a matter for the surrounding runtime environment. main()返回标准C中的int 。此返回值的解释与周围的运行时环境有关。 If you know exactly what you're doing, in some kind of specialized situation where you know that the environment is going to interpret the value in a certain way, then you can cast a pointer to an int. 如果您确切地知道自己在做什么,那么在某种特殊情况下,您就知道环境将以某种方式解释该值,那么您可以将指针转换为int。 But that's nasty. 但这很讨厌。

And be aware that a pointer to dynamically-allocated memory is (probably) meaningless after the program exits anyway! 并且请注意,无论如何程序退出后,指向动态分配的内存的指针(可能)毫无意义! It would only make sense to return a pointer to a fixed address, eg a hardware register in some embedded environment. 仅将指针返回固定地址(例如在某些嵌入式环境中的硬件寄存器)才有意义。

完成phresnel的答案,并回答它是否有用:由于每个进程都有其自己的地址空间,即使您的main()返回一个将用作地址的整数值,自返回指针以来的关键点是什么仅与刚退出的进程的地址空间一致...

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

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