-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.

6
  • 1
    They are function pointers.... Commented Apr 10, 2017 at 10:38
  • 1
    What do you want to initialise them with? Commented Apr 10, 2017 at 10:40
  • @doctorlove to use within a next function - STP_CreateBridge Commented Apr 10, 2017 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. Commented Apr 10, 2017 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. Commented Apr 10, 2017 at 11:12

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.