Search code examples
cpointersparametersimplicit-conversionfunction-declaration

How to correctly initialise function pointer


I want to create a pointer for a function and create a function to initialise this pointer. I'm new to C and can't find example for my problem.

What I have done :

myFile.c :

#include "myFile.h"

void (*PT_MyFunction)(int, bool) = NULL;

void MyFunction (int a, bool b)
{
    if (PT_MyFunction != NULL)
       return (*PT_MyFunction)(a, b);
}

void SetPt (void (*pt)(int, bool))
{
    PT_MyFunction = pt;
}

myFile.h :

extern void MyFunction (int, bool);
void SetPt (void*(int, bool));

I have errors in stdlib.h and I'm unable to fix them. What did I do wrong ?

Edit :

I have many errors stdlib.h: error: storage class specified for parameter 'XXX'. The XXX are variables in this file.

If I comment the line void SetPt (void*(int, bool)); in myFile.h I have no error. My header must be wrong but I don't know how to fix it.


Solution

  • In the source file

    void (*PT_MyFunction)(int, bool) = null;
    

    you probably want :

    void (*PT_MyFunction)(int, bool) =  NULL;
    

    or just

    void (*PT_MyFunction)(int, bool);
    

    because as a global variable the initialization to 0/NULL is done by default

    In the header file

    void SetPt (void*(int, bool));
    

    must be (without naming the parameter) :

    void SetPt (void(*)(int, bool));