简体   繁体   中英

Passing array of functions (with arguments) as argument to function

An extension question to Passing array of functions as argument to function .

I would like to pass an array of functions (with their own arguments) as argument to another function.

Simply, instead of making them void, adding arguments to them.

Code borrowed from the mentioned question:

char *howdy(void) { return "howdy"; }
char *goodbye(void) { return "goodbye"; }

typedef char *(*Charpfunc)(void);

void print(Charpfunc *p)
{
    while (*p) {
        puts((*p)());
        p++;
    }
}

int main()
{
    Charpfunc funcs[] = {
        hello, howdy, goodbye, NULL
    };

    print(funcs);
    return 0;
}

I've tried the obvious solutions, but could not make it work. Most common error was: typedef is initialized (use decltype instead) or converting from one type to another.

I'm not sure what "(with their own arguments)" in your question is suppsed to mean exactly.

Are you looking for something like this?

#include <stdio.h>

char* howdy(int arg) { printf(">howdy: arg = %d\n", arg); return "howdy"; }
char* goodbye(int arg) { printf(">goodbye: arg = %d\n", arg);  return "goodbye"; }

typedef char* (*Charpfunc)(int arg);

void print(Charpfunc* p, int arg)
{
  while (*p) {
    puts((*p)(arg));
    p++;
  }
}

int main()
{
  Charpfunc funcs[] = {
      howdy, goodbye, NULL
  };

  print(funcs, 111);
  print(funcs, 222);
  return 0;
}

or maybe something like this:

#include <stdio.h>

char* howdy(int arg) { printf(">howdy: arg = %d\n", arg); return "howdy"; }
char* goodbye(int arg) { printf(">goodbye: arg = %d\n", arg);  return "goodbye"; }

typedef char* (*Charpfunc)(int arg);

void print(Charpfunc* p, int *arg)
{
  while (*p) {
    puts((*p)(*arg));
    p++;
    arg++;
  }
}

int main()
{
  Charpfunc funcs[] = {
      howdy, goodbye, NULL
  };

  int arg111[] = { 1, 11 };
  int arg222[] = { 2, 22 };
  print(funcs, arg111);
  print(funcs, arg222);
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM