小编The*_*e-Q的帖子

调用一个函数指针,其指定函数的参数少于指针类型

请考虑以下代码:

#include <iostream>

typedef int (*test_func_t) (int, int, int);

int print_integer (int a)
{
    std::cout << "num: " << a << "\n";
    return a;
}

int main (int argc, char * argv[])
{
    test_func_t func = (test_func_t) &print_integer;
    std::cout << "calling with 3 parameters func(5,7,9)\n";
    func(5,7,9);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,类型(test_func_t)被定义为具有3个int参数的函数.函数指针(func)被赋予一个指向"print_integer"的指针,该指针只接收一个参数,然后用3个参数(5,7,9)调用函数指针.

此代码工作并生成"num:5"输出.

gdb disas输出(Intel语法)

disas main
...
   0x080486cb <+9>:     mov    DWORD PTR [esp+0x1c],0x804867d
...
   0x080486e0 <+37>:    mov    DWORD PTR [esp+0x8],0x9
   0x080486e8 <+45>:    mov    DWORD PTR [esp+0x4],0x7
   0x080486f0 <+53>:    mov    DWORD PTR …
Run Code Online (Sandbox Code Playgroud)

c c++ function-pointers calling-convention

2
推荐指数
1
解决办法
666
查看次数

标签 统计

c ×1

c++ ×1

calling-convention ×1

function-pointers ×1