函数指针代码未正确执行

Function pointer code not executing properly

我正在尝试学习函数指针,我只想制作 3 个函数,这些函数具有指向它们的指针,这些函数用于我通过函数指针数组调用的其他 2 个函数。该代码没有给出任何错误,但我收到的是地址而不是值。我试过取消引用等,但没有任何改变。我确定我忽略了一些简单的事情,但我不确定该怎么做,或者我的错误所在。

那里有显式转换,因为我只是在玩弄它,没有特别的原因。

#include <stdio.h>

#include <stdlib.h>

unsigned int par1(void)
{
    return 5;
}

unsigned int par2(void)
{
    return 6;
}

unsigned int par3(void)
{
    return 7;
}

const unsigned int x = 10;


typedef unsigned int (*parPtr)(void);
parPtr parP1 = &par1;
parPtr parP2 = &par2;
parPtr parP3 = &par3;

/** typedef for sum() and scad() */
typedef int (*sumscadPtr)(parPtr, parPtr);

sumscadPtr sumscadPtrArr[2];

int sum(parPtr, parPtr);

int scad(parPtr, const unsigned int);


void allocate_array_of_pointers(void)
{

    sumscadPtrArr[0] = &sum;
    sumscadPtrArr[1] = &scad;


}


// should return 11
int sum(parPtr parA, parPtr parB)
{
    unsigned int value1 = *parA;
    printf("\n%d\n", value1);
    unsigned int value2 = *parB;
    printf("\n%d\n", value2);

    return (int)value1 + (int)value2;
}


// should return 3
int scad(parPtr parA, unsigned const int b)
{
    unsigned int value1 = parA;

    // This is just a simple check in case i might change the const value in the future
    if((int)value1 > (int)b)
        return (int)value1 - (int)b;
    else
        return (int)b - (int)value1;
}




int main()
{
    allocate_array_of_pointers();

    int sumVal = sumscadPtrArr[0](&par1, &par2);
    int scadVal = sumscadPtrArr[1](&par3, x);

    printf("\nsumVal is :%d\n", sumVal);
    printf("\nscadVal is :%d\n", scadVal);

    int a = *parP1;
    printf("\n%d\n", a);


    return 0;
}

您的代码 failed 编译时出现以下错误:

main.cpp:42:24: error: invalid conversion from 'int (*)(parPtr, unsigned int)' {aka 'int (*)(unsigned int (*)(), unsigned int)'} to 'sumscadPtr' {aka 'int (*)(unsigned int (*)(), unsigned int (*)())'} [-fpermissive]
   42 |     sumscadPtrArr[1] = &scad;

这很明显,因为您在 sumscadPtrArr[1] 中存储指向具有不同函数签名的函数的指针,而不是 parPtr

然后:

error: invalid conversion from 'parPtr' {aka 'unsigned int (*)()'} to 'unsigned int' [-fpermissive]
   51 |     unsigned int value1 = *parA;

以及将 * 应用于 parPtr 的所有此类调用的类似错误,这是为了将 parPtr 分配给 unsigned int。正确的方法是

unsigned int value1 = parA();

函数指针可以通过几种方式解除引用:

  1. (*fnPtr)()
  2. fnPtr()

您尝试使用 sumscadPtrArr 创建的函数指针* array/table 理想情况下应该包含相同类型的函数,或者您可以创建一个类似以下内容的结构:

struct fPtrTablle {
    int (*sumFn)(parPtr, parPtr);
    int (*scadFn)(parPtr, const unsigned int);
};

struct fPtrTablle FnTable = { sum, scad};

void initFnTable(void)
{
    FnTable.sumFn =  &sum;
    FnTable.scadFn = &scad;
}

然后从 main() 调用它:

initFnTable();

int sumVal = FnTable.sumFn(&par1, &par2);
int scadVal = FnTable.scadFn(&par3, x);

完整的可编译程序here