-1

I've discovered function pointers in C recently and I'm trying to get it working fine but I'm just pulling my hair on this!!!

I have a pointer to a function returning a string:

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

But I want an array of 6 pointers to function on this but I can't get it working.

I keep getting compiler errors probably with parentheses stuff it's really messy. I've tried something like this but doesn't work:

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

I need help to do this array am I doing something wrong?

teppic
  • 7,051
  • 1
  • 29
  • 35

3 Answers3

2

This is how you define a pointer to a function which return a string :

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

Array :

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

myFuncPtr[0] = myFunc

etc...

giorashc
  • 13,691
  • 3
  • 35
  • 71
  • Thank you for the help i tested it it works good!!! People like @Krishnabhadra dont even respect that some people can be beginners if people on this site are so arrogant as him i wont want to participate here :( – mathuvusalem Apr 24 '12 at 00:58
1

Follow giorashc's answer or use a simple 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

Community
  • 1
  • 1
Zeta
  • 103,620
  • 13
  • 194
  • 236
0

It doesn't look like your initial example is valid. To define a function pointer f that return a pointer to a character array, you should use the following syntax.

char* (*f)() = &func1

If you want an array of function pointers, use the syntax below

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

Here's also a link to a useful old course handout on function pointers.

David Z.
  • 5,621
  • 2
  • 20
  • 13