Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C struct question

Tags:

c

struct

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

like image 285
Pett Avatar asked Dec 13 '22 11:12

Pett


2 Answers

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);
}
like image 81
Joe Avatar answered Dec 30 '22 16:12

Joe


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.

like image 29
Ben Voigt Avatar answered Dec 30 '22 17:12

Ben Voigt