int fn()
{
return 10;
}
int main()
{
printf("%d\n\n",fn);
system("pause");
}
这个节目给一个随机数,但是当一个函数调用时,则返回值10程序用C - 问题中的函数
我可以断定,当我们在使用功能名称printf语句,它给出了一个垃圾值或者有其他一些概念吗?
感谢
int fn()
{
return 10;
}
int main()
{
printf("%d\n\n",fn);
system("pause");
}
这个节目给一个随机数,但是当一个函数调用时,则返回值10程序用C - 问题中的函数
我可以断定,当我们在使用功能名称printf语句,它给出了一个垃圾值或者有其他一些概念吗?
感谢
它应该是:
printf("%d\n\n",fn());
fn
对应功能的ponter地址。这就是为什么你得到垃圾号码。 为了调用函数必须使用圆括号这样的:
foo();
foo(parameter1, ..., parameterN);
非常感谢你Luzhin :) –
FN()不FN
printf("%d\n\n",fn());
非常感谢你 –
忘了打电话的功能:)
变化fn
到fn()
printf("%d\n\n", fn());
现在,您可以通过省略号 - 没有类型检查...
非常感谢你 –
您正在打印fn代码的实际地址在内存中,而不是调用它。呼唤它,你的生活将会光芒四射!
printf("%d\n\n", fn());
而且请在逗号后面放一个空格,就像往常一样。
非常感谢你 –
不需要:D这就是这个网站的要点! – deadalnix
你是不是调用该函数,当你FN(类型),站立着的时候调用这个函数,应该给你正确的结果。(见下文)
int fn()
{
return 10;
}
int main()
{
printf("%d\n\n" , fn());
system("pause");
}
非常感谢你 –
fn()
它将使一个函数调用fn
说,这指的是功能的,那里电话应进行地址所以printf("%d\n\n",fn);
将打印该函数的地址实际上不是一个随机数,并且printf("%d\n\n", fn());
将调用该函数并打印返回的内容。
注意区别:
int fn (void)
{
return 10;
}
int main (void)
{
int x, y;
x = fn();
y = fn;
}
以下是编译器输出:
fn:
push ebp
mov ebp, esp
mov eax, 10
pop ebp
ret
.size fn, .-fn
.globl main
.type main, @function
main:
lea ecx, [esp+4]
and esp, -16
push DWORD PTR [ecx-4]
push ebp
mov ebp, esp
push ecx
sub esp, 20
; below code does x=fn();
call fn ; calls fn, return value in eax
mov DWORD PTR [ebp-12], eax ; stores eax in ebp-12, the location for x on the local stack allocated by compiler
; below code does x=fn;
mov DWORD PTR [ebp-8], OFFSET FLAT:fn ; stores the label address in ebp-8, the location for y on local stack allocated by compiler
add esp, 20
pop ecx
pop ebp
lea esp, [ecx-4]
ret
你应该改变你的printf()语句来此
的printf( “%d \ n” ,fn());
现在,这将工作正常。
欢迎来到SO!请阅读http://stackoverflow.com/questions/how-to-answer。这个答案早就已经给出了。 –
您正在打印一个函数指针。 – SLaks
只需要注意:要打印一个指针,正确的转换说明符是''%p“',并且为了便于移植到奇怪的系统中,指针应该转换为void:'printf(”%p \ '(void *)fn);' – pmg