Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Pointer - Automatic Dereferencing [duplicate]

Possible Duplicate:
How does dereferencing of a function pointer happen?

  void myprint(char* x) {       printf("%s\n", x);    }    int main() {      char* s = "hello";      void (*test)(char*);      void (*test2)(char*);       test = myprint;      test2 = &myprint;       test(s);      (*test)(s);      test2(s);      (*test2)(s);    } 

Can anyone explain to me why all of the above code is valid? "hello" is printed four times. By applying the function pointer, is it implicitly derefenced? Basically I want to know how function pointers are actually stored, because the above is kind of confusing.

like image 613
Sean Nilan Avatar asked Sep 22 '11 17:09

Sean Nilan


People also ask

Does dereferencing a pointer make a copy?

The reason no copy takes place is because a reference is not a machine code level construct. It is a higher level construct and thus is something the compiler uses internally rather than generating specific code for it.

What happens if you dereference a function pointer?

As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function pointer yields the referenced function, which can be invoked and passed arguments just as in a normal function call.

What is pointer dereferencing?

Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. *(asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers.

How do you dereference a pointer to a function in C?

As we already know that "what is a pointer", a pointer is a variable that stores the address of another variable. The dereference operator is also known as an indirection operator, which is represented by (*). When indirection operator (*) is used with the pointer variable, then it is known as dereferencing a pointer.


1 Answers

This is just a quirk of C. There's no other reason but the C standard just says that dereferencing or taking the address of a function just evaluates to a pointer to that function, and dereferencing a function pointer just evaluates back to the function pointer.

This behavior is (thus obviously) very different from how the unary & and * operators works for normal variables.

So,

test2 = myprint; test2 = &myprint; test2 = *myprint; test2 = **********myprint; 

All just do exactly the same, gives you a function pointer to myprint

Similarly,

test2(s); (*test2)(s); (***********test2)(s); 

Does the same, call the function pointer stored in test2. Because C says it does.

like image 127
nos Avatar answered Oct 18 '22 05:10

nos