0

Given

void* hello () {
   cout << "Test.\n";          
}

and

struct _table_struct {
    void *(*hello) ();
};

How do we assign the function (hello) to the function member pointer?

I tried this (in main):

 _table_struct g_table;
 _table_struct *g_ptr_table = &g_table;

 // trying to get the struct member function pointer to point to the designated function
 (*(g_ptr_table)->hello) =  &hello; // this line does not work

 // trying to activate it
 (*(g_ptr_table)->hello)();
Ursa Major
  • 851
  • 7
  • 25
  • 47
  • 4
    There's a problem here. The function pointer points to a function that returns `void*`, but you have a function that returns `void`. – Brian Bi Mar 11 '15 at 00:09
  • @Brian, could you emend the above code to illustrate how to correct it, so that we may call it and run to invoke the function? The function within the struct has to remain void *(*hello) (); – Ursa Major Mar 11 '15 at 00:14
  • Not without knowing what the purpose of the member `hello`. You could change the `hello` function, perhaps, to return a null pointer, but what if the `_table_struct` expects to be able to access memory through the pointer returned? – Brian Bi Mar 11 '15 at 00:17
  • @Brian, could you give an example where i can invoke the hello() by calling the function member in main? – Ursa Major Mar 11 '15 at 00:19
  • @Brian, I did this, but to no avail. void* hello () { cout << "Test.\n"; return 0; } – Ursa Major Mar 11 '15 at 00:59
  • @UrsaMajor Please post complete, minimal code that shows what you *tried*. – Brian Bi Mar 11 '15 at 01:18
  • @Brian, I emended the comments above on what was tried. Thank you. – Ursa Major Mar 11 '15 at 01:36

1 Answers1

1

You don't dereference a pointer when assigning it to point to an object.

g_ptr_table->hello = &hello; // note: the & is optional
g_ptr_table->hello(); // dereferencing the function pointer is also optional
Brian Bi
  • 111,498
  • 10
  • 176
  • 312