-1

I have read similar threads on SO on this topic (How to initialize a Pointer to a struct in C? and Initializing a pointer to a structure) but failed trying new or malloc. I've got a bunch of typedefs like

typedef void  (*STP_CALLBACK_ON_TOPOLOGY_CHANGED)       (BRIDGE* bridge);
typedef void* (*STP_CALLBACK_ALLOC_AND_ZERO_MEMORY)     (unsigned int size);
typedef void  (*STP_CALLBACK_FREE_MEMORY)               (void* p);
typedef void  (*STP_CALLBACK_ENABLE_LEARNING)           (BRIDGE* bridge, unsigned int portIndex, unsigned int treeIndex, bool enable);

which form a structure

    struct STP_CALLBACKS
    {
      STP_CALLBACK_ON_TOPOLOGY_CHANGED      onTopologyChanged;
      STP_CALLBACK_ALLOC_AND_ZERO_MEMORY    allocAndZeroMemory;
      STP_CALLBACK_FREE_MEMORY              freeMemory;
      ...
    };

and when I want to init a pointer to this structure with

const STP_CALLBACKS *callbacks = new STP_CALLBACKS;

It actually inits nothing. I'm quite a newbie and obviously miss something important. What is a correct way to do it?

P.S. the code above is from mstp-lib. I'm on VS2015.

Community
  • 1
  • 1
Alexandr
  • 155
  • 2
  • 3
  • 13
  • 1
    They are function pointers.... – Sourav Ghosh Apr 10 '17 at 10:38
  • 1
    What do you want to initialise them with? – doctorlove Apr 10 '17 at 10:40
  • @doctorlove to use within a next function - [STP_CreateBridge](https://sourceforge.net/p/mstp-lib/code/HEAD/tree/trunk/_help/STP_CreateBridge.html) – Alexandr Apr 10 '17 at 10:44
  • 2
    You didn't tell it to initialise the contents. Since you declared it const, you'll have a hard time setting members unless you define a constructor. You don't need dynamic allocation. You just need to decide what functions to point at, or set them to nullptr. – paddy Apr 10 '17 at 10:51
  • I didn't ask why - I asked what. You need to tell it what the functions pointers should point to. If you show what functions you want it to point to, we can show you how. – doctorlove Apr 10 '17 at 11:12
  • I suggest that you take a pick from [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Apr 10 '17 at 11:26

1 Answers1

1

Cause you are not actually initializing. Typedef just declares a type. All what new does above is allocating memory for 4 function pointers. To initialize this memory you need constructor:

struct STP_CALLBACKS { 
    STP_CALLBACKS(STP_CALLBACK_ON_TOPOLOGY_CHANGED _fp1, ...
...

Then, having actual functions to be called like func1, func2, ... you can initialize your structure:

void func1(BRIDGE* bridge) {
   ...
}

STP_CALLBACKS callbacks(func1, ...

And then call back your functions:

BRIDGE bridge;
callbacks.onTopologyChanged(&bridge);
Spock77
  • 3,256
  • 2
  • 30
  • 39