C ++函数指针导致seg错误

时间:2014-08-12 17:27:17

标签: c++ function pointers segmentation-fault

我有点麻烦。我似乎无法弄清楚为什么我的主函数不能调用intFunction指向的函数而没有seg错误。

此外,这是我用于测试目的的代码。我还是C ++的新手。

感谢您的帮助。

#include <iostream>

int tester(int* input){
    std::cout << "\n\n" << *input << "\n\n";
}

int (*intFunction)(int*);

template<typename FT>
int passFunction(int type, FT function){
    if(type == 1){
        function = tester;
        //Direct call...
        tester(&type);
        int type2 = 3;
        //Works from here...
        function(&type2);
    }
    return 0;
}

int main(int argc, char* argv[]){
    passFunction(1,intFunction);
    int alert = 3;
    //But not from here...
    intFunction(&alert);
    return 0;
}

1 个答案:

答案 0 :(得分:1)

当将函数指针作为参数传递时,它们与其他变量没有任何区别,因为您传递的是值的副本(即当时它具有的任何函数地址)。

如果您想在另一个函数中分配变量,则必须通过引用或作为指向原始变量的指针传递它。

参考:

int passFunction(int type, FT& function)

或作为指针

int passFunction(int type, FT* ppfunction)
{
    if(type == 1)
    {
        *ppfunction = tester;
        //Direct call...
        tester(&type);
        int type2 = 3;
        //Works from here...
        (*ppfunction)(&type2);
    }
    return 0;
}

// which then requires you pass the address of your variable when
// calling `passFunction`

passFunction(1, &intFunction);
相关问题