C 中的函数指针
为什么下面打印 1
.我期望它打印函数指针的地址。
#include <stdio.h>
int main(main) {
printf("%i",main);
return 0;
}
Why does the following print 1
. I was expecting it to print the address of the function pointer.
#include <stdio.h>
int main(main) {
printf("%i",main);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
指针必须用
%p
打印。无论如何,这里存在一个“别名”问题,相当奇怪,但就是这样:main 获取函数 main 的第一个参数的值,即通常称为“argc”的值。如果你用更多的参数调用它,你应该看到更大的数字。Pointers must be printed with
%p
. Anyway here there's an "aliasing" problem, rather odd but that's it: main gets the value of the first argument to function main that is, what usually is called "argc". if you call it with more arguments, you should see bigger number.因为程序的
main
函数的第一个参数是运行时的参数计数(加一,因为程序的名称是第一个参数)。假设您在不带参数的情况下调用程序,则该值将使用整数填充。许多人传统上使用带有以下签名的
main
:如果删除该参数,您可能会得到您想要的:
如果这不起作用,请尝试声明
int main();
位于函数定义之上。如果这不起作用,首先问问自己为什么要这样做。 :-P
Because the first argument of a program's
main
function is the argument count (plus one, since the program's name is the first argument) at runtime. Assuming you invoked your program with no arguments, that value will be populated with an integer.Many people traditionally use
main
with the following signature:If you remove the parameter, you might get what you want:
If that doesn't work, try declaring
int main();
above the function definition.If THAT doesn't work, ask yourself why you're doing this in the first place. :-P
您声明了一个名为“
main
”的参数 - 该参数对应于C
中main
函数的第一个参数,而该参数通常是称为“argc
”,如果您在没有任何命令行参数的情况下启动程序,则该值为 1。you declared a param with the name "
main
" - this param corresponds to the first param of themain
function inC
which in turn is usually called "argc
" which in turn is 1 if you start you program whithout any commandline params.main 的第一个参数通常称为 argc ,它告诉您程序运行时使用了多少个参数。由于您在没有参数的情况下运行此命令,因此该值将为 1(可执行文件的名称)。如果您从命令行运行此命令并使用空格分隔的额外参数,则该数字将会增加。
The first parameter to main is usually called
argc
which tells you how many arguments the program was run with. Since you are running this with no arguments the value will be 1 (The name of the executable) If you run this from command line with extra arguments separated by spaces that number will increase.这相当于
所以
main
是main
函数的第一个参数。如果不带参数调用,则 argv 数组(通常在后面)的大小为 1,argv[0] 保存进程的名称。This is equivalent to
So
main
is the first parameter of themain
function. If called without parameters the size of the (normally following) argv array is 1, argv[0] holding the name of the process.您将
main
作为参数添加到函数main
中。这将获取通常赋予main
的第一个值,即传递给程序的参数的大小。如果不向程序传递参数,参数仍然保存正在执行的程序的名称,因此参数列表的大小为 1,即打印的内容。You include
main
as a parameter to the functionmain
. This gets the first value normally given tomain
, that is, the size of the arguments passed to the program. If you don't pass arguments to the program, still the arguments hold the name of the program being executed, so the size of the argument list is 1, what it is printed.