lushl9301
lushl9301

Reputation: 25

what's the difference between int (* f [])(); and int f[]();

i find this in Pointers on C

int f[]();  /* this one is illegal */

and:

int (* f [])(); /* this one legal. */

i really want know what's the usage of the second one.

thank you.

Upvotes: 2

Views: 4873

Answers (4)

j_random_hacker
j_random_hacker

Reputation: 51326

int f[]();  /* this one is illegal */

That's trying to declare an array of functions, which is impossible.

int (* f [])(); /* this one NOT legal, despite what the OP's post says. */

That's trying to declare an array of function pointers, which would be perfectly legal (and sensible) if the array size were specified, e.g.:

int (* f [42])(); /* this one legal. */

EDIT: The type int (* f [])() can be used as a function parameter type, because for function parameter types, array-to-pointer conversion takes place immediately, meaning we don't ever need to specify the dimension of the innermost array of a (possibly multidimensional) array:

void some_func(int (* f [])());  /* This is also legal. */

Upvotes: 1

Omkant
Omkant

Reputation: 9234

int f[](); // this is illegal because of you can't create array of functions . It's illegal in C

But second is legal

int (* f [])(); It says that f is an array of function pointers returning int and taking unspecified number of arguments

Upvotes: 1

raina77ow
raina77ow

Reputation: 106483

The second example is quite valid, if you use initialization block. For example:

#include <stdio.h>
int x = 0;
int a() { return x++ + 1; }
int b() { return x++ + 2; }
int c() { return x++ + 3; }

int main() 
{
  int (* abc[])() = {&a, &b, &c};
  int i = 0,
      l = sizeof(abc)/sizeof(abc[0]);
  for (; i < l; i++) { 
    printf("Give me a %d for %d!\n", (*abc[i])(), i);
  }
  return 0;
}

Upvotes: 2

Rudolfs Bundulis
Rudolfs Bundulis

Reputation: 11954

I'm not sure if the second example is legal, since the size of the function array is not known, but what it is supposed to be is an array of function pointers, and here is a possible example of usage if the size would be known:

int a()
{
    return 0;
}

int main(int argc ,char** argv)
{
    int (* f [1])();
    f[0] = a;
}

Upvotes: 1

Related Questions