Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointer accepting argument

int (*ptr)(char (*ch)[]);

What does the above declaration means? Does it mean

ptr is pointer to a function that accepts an argument which is array of pointers to characters returning integer?

How to evaluate?

like image 442
Rohit Avatar asked Jun 10 '13 18:06

Rohit


2 Answers

ptr is pointer to a function that accepts an argument which is a pointer to an array of characters, returning integer.

like image 60
Ziffusion Avatar answered Sep 20 '22 11:09

Ziffusion


There's rule: http://ieng9.ucsd.edu/~cs30x/rt_lt.rule.html

Briefly, you should start from identifier, then parse everything from identifier to the right (it can be () - function or [] array), then parse everything from identifier to the left. Parentheses changes this order - you should parse everything in the most inner parentheses first and so on, it works like with arithmetic calculations.

In other words, there is an order of precedence (which can be changed by parentheses), from higher to lower:

1) () - function and [] - array, from left to right;

2) * - pointer, type, type modifier, from right to left.


Your example

int (*ptr)(char (*ch)[])

We start from identifier

int (*ptr)(char (*ch)[]);  // (1)ptr
      |_|                      
       1

Identifier ptr is in parentheses, so we parse everything in parenteses first

(*ptr)  // (1)ptr
  |_|       
   1

There's nothing to the right, so we parse to the left

(*ptr)  // (1)ptr is (2)a pointer
 ||_|       
 2 1

We finished in parentheses, now we parse to the right of parentheses

int (*ptr)(char (*ch)[]);  // (1)ptr is (2)a pointer to (3)function
     ||_| |____________|
     2 1        3

So far we ignore function arguments and parse to the left of parentheses

int (*ptr)(char (*ch)[]);  // (1)ptr is (2)a pointer to (3)function which returns (4)int
|_| ||_| |____________|
 4  2 1        3

In the same way we parse argument of function (I've inserted some spaces for better alignment)

char  (* ch )[ ]  // (1)ch is (2)a pointer to (3)array of (4)chars
|___|  | |_| |_|
  4    2  1   3

Finally, we have:

ptr is a pointer to function which returns int and accepts a pointer to array of chars as argument

like image 29
kotlomoy Avatar answered Sep 22 '22 11:09

kotlomoy