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

标签 c++ function pointers segmentation-fault

我遇到了一些麻烦。我似乎无法弄清楚为什么我的 main 函数不能在没有段错误的情况下调用 intFunction 指向的函数。

此外,这是我用于测试目的的代码。我对 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;
}

最佳答案

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

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

引用:

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

关于指向函数的 C++ 指针导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25270471/

相关文章:

c++ - 如何让 clang-tidy 依次应用 FixItHints,一个接一个?

c++ - 具有约束/概念的类模板特化

c++打印包含结构的 vector

c - 将函数传递给函数时,错误左值需要作为一元 '&' 操作数

c - 使用 scanf %p UB

c++ - 使用指针访问 QVector 的元素

c++ - 继承自QLabel的类,为什么不调用自定义槽?

c - 如何修改已传递给 C 函数的指针?

php - WordPress 在调整大小后删除原始图像?

c - 为什么我的 C 代码出错