I am trying to create a linked list in C but trying to pack it nicely in somewhat of a C++ style class. I am having some issues however using function pointers in C.
<
You can have an uninitialized function pointer just fine as long as you don't actually use it. If you do want to use it to call a function, then obviously you have to assign a function to it. C is unable to guess which function you want to use.
If you have a linked list structure where sometimes you need a function, and sometimes you don't, then just assign NULL
to it when you create the list, and have your list implementation only call the function when it's not NULL
.
If it always points to the same function, then just do the assignment in your constructor function.
You need to assign the function to the member. i also recommend giving them different names:
typedef void (*addMSGFunc)(unsigned char *, int, struct linkedList *);
typedef struct linkedList {
int count;
struct msgNode *front;
struct msgNode *back;
addMSGFunc addMSG;
} msgList;
void addMSGImpl(unsigned char *data, int size, struct linkedList *self)
{
...
}
And then after creating a msgList:
msgList myList;
myList.addMSG = addMSGImpl;
Well you can't add a default value in the declaration of the struct but what you can do is:
linkedList
instance - I guess you've seen that in C style librariesLike:
void addMSG(unsigned char *data, int size, struct linkedList *self);
struct linkedList {
int count;
struct msgNode *front;
struct msgNode *back;
void (*addMSG)(unsigned char *, int, struct linkedList *);
} DefaultList = {0, NULL, NULL, addMSG};