回调函数误解

标签 c callback function-pointers

这是问的问题: What is a “callback” in C and how are they implemented?

那个问题的答案之一是这样的: (我稍微修改以打印该值)

#include <stdio.h>
#include <stdlib.h>


void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{
    for (size_t i=0; i<arraySize; i++) {
        array[i] = getNextValue();
        printf("%d\n", array[i]);  // This is what I added
      }

}

int getNextRandomValue(void)
{
    return rand();
}

int main(void)
{
    int myarray[10];
    populate_array(myarray, 10, getNextRandomValue);
}

现在我的问题是上面的回调函数有什么用,什么时候我也可以不用回调来做?

#include <stdio.h>
#include <stdlib.h>


void populate_array(int *array, size_t arraySize, int getNextValue(void))
{
    for (size_t i=0; i<arraySize; i++) {
        array[i] = getNextValue();
        printf("%d\n", array[i]);
      }

}

int getNextRandomValue(void)
{
    return rand();
}

int main(void)
{
    int myarray[10];
    populate_array(myarray, 10, getNextRandomValue);
}

另外,能否请您给我一个简单函数无法完成的回调函数的真实示例?

最佳答案

Now my question is the what is the use of callback function in above, when I can do it without callback also?

没什么,真的 - 这不是一个真实的例子,它只是为了解释回调是如何工作的。

Also, can you please give me real example of callback function which cannot be done with simple function?

cURL library当它需要用户提供数据时(例如,当发出 HTTP POST 请求时)或当它想要通知用户数据检索时(例如,当服务器发送 HTTP header 时),使用读、写和各种其他回调函数.虽然这可以使用临时缓冲区、动态内存分配和“属性 setter ”函数来完成,但使用回调函数方法更方便(即需要更少的跑腿)。

关于回调函数误解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17747369/

相关文章:

javascript - React - 组件中的回调

javascript - while循环javascript的回调方法

c++ - 函数调用中多个星号有什么用?

c++ - Constexpr 函数指针作为模板参数 MSVC vs GCC

c - 是否可以使用 struct stat 描述符获取和设置文件名?

c - 删除链接排序列表中的第一个元素

c - Linux 和 C : 'write()' does not write anything to file

c - 是什么导致 -EPERM 返回为 4294967295?

delphi - 在使用包编译的 dll 和不使用包编译的 dll 之间处理回调方法是否安全(Delphi)?

c - 我们应该在哪个内存段中找到C中函数的内存地址