C - 在可变函数中将多个函数地址作为参数传递

标签 c function-pointers memory-address variadic-functions

我正在尝试编写一个函数,它将采用前 n 个整数和可变数量的函数,并构建一个表,该表的第一列中的数字为“i”,其他列中的数字为“function(i)” .

但我似乎无法将我的函数地址传递给表生成器,因为我遇到了访问冲突错误。我做错了什么?

#include <stdio.h>
#include <math.h>
#include <stdarg.h>

typedef float(*f)(float);

// Some examples of f-type functions.
float square(float x) { return x*x; };
float root(float x) { return sqrt(x); };
float timesPi(float x) { return x * 3.14; };

// Display a table with first colon being the numbers from 1 to n, 
// then the other columns to be f(i)
void table(unsigned int n, unsigned int nr_functions, ...)
{
    va_list func;
    va_start(func, nr_functions);

    for (float i = 1; i <= n; i += 1)
    {
        printf("\n%6.0f |", i);
        for (unsigned int j = 0; j < nr_functions; j++)
        {
            f foo = va_arg(func, f);
            printf("%6.3f |", foo(i));
        }
        va_end(func);
    }
}

// Main function
int main()
{
    table(5, 3, &square, &root, &timesPi);
    system("pause");
    return 0;
}

对于上面的例子

table(5, 3, &square, &root, &timesPi);

我想回去

1   |   1.000 |  3.140 |
2   |   1.141 |  6.280 |
3   |   1.732 |  9.420 |
4   |   2.000 | 12.560 | 
5   |   2.236 | 15.700 |

最佳答案

您需要重用参数列表的变量部分,这意味着您需要在正确的位置使用 va_start()va_end() — 在外循环内:

void table(unsigned int n, unsigned int nr_functions, ...)
{
    for (unsigned int i = 1; i <= n; i++)
    {
        va_list func;
        printf("\n%6.0f |", (double)i);
        va_start(func, nr_functions);
        for (unsigned int j = 0; j < nr_functions; j++)
        {
            f foo = va_arg(func, f);
            printf("%6.3f |", foo(i));
        }
        va_end(func);
    }
}

否则,除非您在循环内调用了 va_end(),否则您将离开列表的末尾,导致天知道会造成什么损害。

请注意,循环应该使用整数运算——随之而来的是对 printf() 的更改——这里我转换了值,但是将格式更改为 %6d 会也要保持理智(事实上可能更好)。

使用这个函数,我得到了输出:

 1 | 1.000 | 1.000 | 3.140 |
 2 | 4.000 | 1.414 | 6.280 |
 3 | 9.000 | 1.732 | 9.420 |
 4 |16.000 | 2.000 |12.560 |
 5 |25.000 | 2.236 |15.700 |

关于C - 在可变函数中将多个函数地址作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34362543/

相关文章:

delphi - 如何将程序地址保存在数组中,然后在Delphi中使用它们

c++ - 声明指针变量时,内存分配给指针的名称还是指针的地址?

c - 汇编中有关 win32 api 的帮助

c++ - 如何获取进程中使用的 .DLL 的(物理)基地址?

c - 如何在 OpenMP 中实现并行化

c++,指向函数 vector 的指针的STL映射

c# - 从 C# 调用包含函数指针的 DLL 函数

c++ - 指针类定义

编译器提示宏中未声明的变量

c - 在C中动态分配结构的就地定义