【问题标题】:How to pass the result of a function pointer as an argument for another function?如何将函数指针的结果作为另一个函数的参数传递?
【发布时间】:2021-08-27 17:05:15
【问题描述】:

好的,这是我在 StackOverflow 上的第一篇文章,我已经为此尝试了一切。所以第一条指令是我需要在结构中创建一个函数指针。到目前为止没有任何问题。

typedef struct Function2D {
    float (*Fun2D) (float);
}Function2D;

老师希望这个结构函数指针将给定的浮点数乘以 2。我已经这样做了。

int main() 
{
    Function2D Funcion;
    Funcion.Fun2D = Test;
    Funcion.Fun2D(10000);
    return 0;
}
float Test (float n)
{
    n = n*2;
    return n;
}

但是我老师想实现另一个函数,它在获取数据类型 Function2D 或乘法结果后返回布尔值。 有没有办法在不硬编码值的情况下从结构中访问函数指针的结果?

【问题讨论】:

  • 我不认为我理解这个问题。你能给出一个你想到的伪代码示例吗?
  • 你的问题我不清楚。请edit 重新表述您的问题。我不明白这句话:但是我老师想实现另一个函数,在获得数据类型 Function2D 或乘法结果后返回布尔值。 我也不确定我是否理解最后一句话的问题。你的意思是像float result; result = Funcion.Fun2D(10000);这样的东西吗?
  • "我已经为此尝试了一切" --> 非常令人印象深刻。
  • 您可以使用如下语句访问函数返回的值:result = function(argument); function 是常规函数还是结构中的函数指针或其他任何内容都没有关系。
  • 谢谢各位,问题是我他妈是智障。老师只要求将每个函数指针定义为函数,例如 float (*Fun2D) (float); 为 Function2D。现在我要弄清楚的是如何访问函数指针/函数返回的值

标签: c struct function-pointers


【解决方案1】:

如果我正确理解你的问题,那么你问的是如何实现一个函数

  • 返回一个将函数作为参数的布尔值

  • 将包含函数指针的结构作为参数。

  • 将调用结果传递给另一个函数的函数指针。

这是三个例子:

#include <stdio.h>

// Define the types for the function pointers you need
typedef float (*FloatFunc) (float);
typedef bool (*BoolFunc) (FloatFunc);

// Declare a structure containing each of the function pointer types defined above.
typedef struct StructContainingFunctionPointers {
    FloatFunc FunFloat;
    BoolFunc  FunBool;
} StructContainingFunctionPointers;

// Declare a function of the same type as FloatFunc
float MultiplyBy2(float n)
{
    n = n * 2;
    return n;
}

// Declare a function of the same type as BoolFunc
bool TestIfMultiplyBy2(FloatFunc func)
{
    return func(2) == 4;
}

// Declare a function that takes StructContainingFunctionPointers as an argument
void TestStructContainingFunctionPointers(StructContainingFunctionPointers Rec) {
    // Do a smoke-test of FunFloat
    float result = Rec.FunFloat(10000);
    // Pass the result of Rec.FunFloat to printf()
    printf("Calling FunFloat(10000) returned %.0f.\n", result);
    if (result == 10000 * 2)
        printf("The float function seems to work.\n");
    else
        printf("The float function DOES NOT work.\n");

    // Do a smoke-test of FunBool
    if (Rec.FunBool(Rec.FunFloat))
        printf("The bool function seems to work.\n");
    else
        printf("The bool function DOES NOT work.\n");
}

int main()
{
    // Initialize the record.
    StructContainingFunctionPointers Rec;
    Rec.FunFloat = MultiplyBy2;
    Rec.FunBool = TestIfMultiplyBy2;
    // Test
    TestStructContainingFunctionPointers(Rec);
    // Return success
    return 0;
}

这是程序的输出:

Calling FunFloat(10000) returned 20000.
The float function seems to work.
The bool function seems to work.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 2015-01-29
    • 1970-01-01
    • 2021-07-18
    相关资源
    最近更新 更多