简体   繁体   English

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

[英]C++ pointer to function results in seg fault

I'm having a bit of trouble. 我有点麻烦。 I can't seem to figure out why my main function can't call the function pointed to by intFunction without a seg fault. 我似乎无法弄清楚为什么我的主函数在没有seg错误的情况下不能调用intFunction指向的函数。

Also, this is code that I'm using for testing purposes. 另外,这是我用于测试目的的代码。 I'm still fairly new to C++. 我还是C ++的新手。

Thanks for your help. 谢谢你的帮助。

#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;
}

When passing function pointers as parameters, they are not any different than other variables in that you are passing a copy of the value (ie whichever function address it has at the time). 当将函数指针作为参数传递时,它们与其他变量没有什么不同,因为您传递的是值的副本(即,它当时具有的函数地址)。

If you are wanting to assign a variable in another function, you have to either pass it by reference or as a pointer to the original variable. 如果要在另一个函数中分配变量,则必须通过引用传递它或将其作为指向原始变量的指针。

By reference: 引用:

int passFunction(int type, FT& function)

Or as a pointer 或作为指针

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);

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

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