C struct question

I have an interface documented as follows:

typedef struct Tree { int a; void* (*Something)(struct Tree* pTree, int size); }; 

Then, as I understand it, I need to instantiate this object and use the Something method to put the value for 'size'. Therefore i do

 struct Tree *iTree = malloc(sizeof(struct Tree)); iTree->Something(iTree, 128); 

But it cannot be initialized. Am I doing it right? Howcome the first member of the Something method is a pointer to the same structure?

Can someone please explain?

thanks

+4
source share
3 answers

You need to set Something to something, because it is just a pointer to a function, not a function. The structure you created with malloc just contains garbage fields and structures that need to be set before they are useful.

 struct Tree *iTree = malloc(sizeof(struct Tree)); iTree->a = 10; //<-- Not necessary to work but you should set the values. iTree->Something = SomeFunctionMatchingSomethingSignature; iTree->Something(iTree, 128); 

Update

 #include <stdlib.h> #include <stdio.h> struct Tree { int a; //This is a function pointer void* (*Something)(struct Tree* pTree, int size); }; //This is a function that matches Something signature void * doSomething(struct Tree *pTree, int size) { printf("Doing Something: %d\n", size); return NULL; } void someMethod() { //Code to create a Tree struct Tree *iTree = malloc(sizeof(struct Tree)); iTree->Something = doSomething; iTree->Something(iTree, 128); free(iTree); } 
+8
source

This is a virtual function of a poor person. The initial parameter is roughly equivalent to the C ++ this pointer in the member function. And you must manually set function pointers before calling them, while C ++ virtual functions are configured by the compiler.

+4
source

The Tree::Something element is never initialized. You allocate space for the Tree , but the distribution is different from initialization, and the allocated Tree contains only irreproducible bits.

+1
source

All Articles