C - 指向返回字符串的函数的指针函数的指针数组

时间:2012-04-23 07:12:44

标签: c pointers

我最近在C中发现了函数指针,我试图让它工作正常,但我只是把它拉到头上!!!

我有一个指向返回字符串的函数的指针:

(char *) (*)() (*bar)().

但是我想要一个包含6个指针的数组来运行,但是我无法让它工作。

我不断得到编译错误,可能是括号中的东西,它真的很乱。我尝试过类似的东西但不起作用:

(((char)(*))((*))(((*)((foo))))([(6)]));

我做错了这个数组我需要帮助吗?

3 个答案:

答案 0 :(得分:2)

这是如何定义一个返回字符串的函数的指针:

(char *) (*myFuncPtr)() = myFunc

数组:

(char *) (*myFuncPtr[6])();

myFuncPtr[0] = myFunc
等等......

答案 1 :(得分:1)

关注giorashc's answer或使用简单的typedef

#include <stdio.h>

typedef const char * (*szFunction)();

const char * hello(){ return "Hello";}
const char * world(){ return "world";}
const char * test(){ return "test";}
const char * demo(){ return "demo";}
const char * newline(){ return "\n";}
const char * smiley(){ return ":)";}

int main()
{
    unsigned int i = 0;
    szFunction myFunctions[6];
    myFunctions[0] = hello;
    myFunctions[1] = world;
    myFunctions[2] = test;
    myFunctions[3] = demo;
    myFunctions[4] = newline;
    myFunctions[5] = smiley;

    for(i = 0; i < 6; ++i)
        printf("%s\n",myFunctions[i]());
    return 0;
}

Ideone demo

答案 2 :(得分:0)

看起来您的初始示例无效。要定义返回指向字符数组的指针的函数指针f,应使用以下语法。

char* (*f)() = &func1

如果需要函数指针数组,请使用以下语法

char* (*arrf[6])() = { &func1, &func2, &func3, &func4, &func5, &func6 }

这里还有一个指向useful old course handout函数指针的链接。