function_pointer_1

Jun 30, 2012 at 3:27pm
Hello.
Assuming the following definitions:
1
2
3
int add(int a, int b)
{return a + b;}
int (*op)(int a, int b)=  add;


Why is the call
*op = add + 1;


wrong after the line
int (*op)(int a, int b)= add;
?

Thanks in advance!
Jun 30, 2012 at 3:38pm
*op = add + 1; ¿what do you think you are doing there?
Jun 30, 2012 at 4:24pm
I am after the reason for the syntax error.All of them.
Last edited on Jun 30, 2012 at 4:28pm
Jun 30, 2012 at 5:04pm
You dereference a function pointer, and then try to assign it to a function (ie. the address of that function) plus one? This makes no sense. What are you trying to accomplish?
Jul 1, 2012 at 6:31am
I am not.the exam question had four options.On of which was this.
I now look for the reqasons for the error.
Last edited on Jul 1, 2012 at 6:32am
Jul 1, 2012 at 6:52am
You can't do pointer arithmetic with a function's address.
Also, I believe dereferencing a function pointer will just give you the address right back.
1
2
3
4
5
6
7
*p;
**p;
***p;
****p;
//They all do the exact same thing.
//You can do this too:
int a = (******p)(1,1);
Jul 1, 2012 at 9:48am
> I now look for the reqasons for the error.

The binary + operator is available only for pointers that point to a complete object.
In particular. T* pointer ; pointer + 1 ; requires that T is a complete type - sizeof(T) is known at compile-time.

A function is not an object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct A ;

int main()
{
    typedef int function_type( int, int ) ;
    function_type* p1 /* = ... */ ;
    void* p2 /* = ... */
    A* p3 /* = ... */

    sizeof( function_type ) ; // *** error - not an object 
    sizeof( void ) ; // *** error - void is deemed to be an incomplete type
    sizeof( A ) ; // *** error - A is an incomplete type

    function_type a1[1] ; // *** error
    void a2[1] ; // *** error 
    A a3[1] ; // *** error - A is an incomplete type

    p1 + 1 ; // *** error - p1 does not point to an object
    p2 + 1 ; // *** error - p2 does not point to a complete object
    p3 + 1 ; // *** error - p3 does not point to a complete object
}
Topic archived. No new replies allowed.