使用函数指针编译测试程序中的错误

时间:2013-05-06 17:44:03

标签: c compiler-errors function-pointers

我编写了一个简单的C程序来学习函数指针的用法:

#include <stdio.h>

int (*workA) ( char *vA );
int (*workB) ( char *vB );

int main( int argc, char * argv[] )
{
    char *strA = "Hello.";
    char *strB = "Bonjour.";

    int a = workA(strA);
    int b = workB(strB);

    printf("Return value of A = %d, B = %d.\n", a, b);

    return 0;
}

int (*workA)( char *vA )
{
    printf("A: %s\n", vA); // line 20

    return 'A';
}

int (*workB)( char *vB )
{
    printf("B: %s\n", vB); // line 27

    return 'B';
}
海湾合作委员会抱怨:

test.c:20: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token
test.c:27: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

我不知道它有什么问题。任何评论都将受到高度赞赏。

2 个答案:

答案 0 :(得分:2)

workAworkB是两个函数的指针。您需要声明将执行该工作的实际函数,然后在调用它们之前将它们分配给您的两个指针...

#include <stdio.h>

int (*workA) ( char *vA );
int (*workB) ( char *vB );

int workAFunction( char *vA )
{
    printf("A: %s\n", vA); // line 20

    return 'A';
}

int workBFunction( char *vB )
{
    printf("B: %s\n", vB); // line 27

    return 'B';
}

int main( int argc, char * argv[] )
{
    char *strA = "Hello.";
    char *strB = "Bonjour.";

    workA = workAFunction;
    workB = workBFunction;

    int a = workA(strA);
    int b = workB(strB);

    printf("Return value of A = %d, B = %d.\n", a, b);

    return 0;
}

答案 1 :(得分:0)

当您编写int (*workA) ( char *vA )时,表示 workA 是指向返回int的函数的指针。 workA 不是一个函数。

删除*workA周围的括号,只需编写int (*workA) ( char *vA )即可使workA函数返回指向int的指针。

同样适用于工作B.

你可以使用这个名为cdecl的优秀程序来缓解问题。