Pett
Pett

Reputation: 43

C struct question

I have a interface documented like this:

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

Then as I understand I need to create instance of it, and use Something method to put the value for 'size'. So I do

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

But it keeps failing to initialize. Am I doing this right? Howcome the first member of the Something method is pointer to the very same struct?

Can anyone explain please?

Thanks

Upvotes: 4

Views: 269

Answers (3)

Joe
Joe

Reputation: 57169

You have to set Something to something since it is only a function pointer and not a function. The struct you created with malloc just contains garbage and struct fields need to be set before it is 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);
}

Upvotes: 8

Sebastian Mach
Sebastian Mach

Reputation: 39089

The member Tree::Something is never initialized. You allocate space for a Tree, but allocation is different from initialization, and your allocated Tree contains only unmeaningful bits.

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283624

This is a poor man's virtual function. The initial parameter is roughly equivalent to C++'s this pointer in a member function. And you must manually set the function pointers before calling them, whereas C++ virtual functions are set up by the compiler.

Upvotes: 4

Related Questions