what does null function pointer in C mean?

后端 未结 2 336
梦如初夏
梦如初夏 2021-01-21 15:24

Say we have a function pointer:

void (*func0)(void);

which is also defined:

void func0(void) { printf( \"0\\n\" ); }

相关标签:
2条回答
  • 2021-01-21 16:01

    It is undefined behaviour to de-reference a null pointer. The fix is simply to ensure that the pointer refers to an appropriate function.

    In your case you want something like this:

    void MyFunction(void)
    {
        printf( "0\n" ); 
    }
    

    and then later you can assign to func0:

    func0 = &MyFunction;
    

    Note that I am using a different name for the function pointer variable and the actual function.

    And now you can call the function, via the function pointer:

    func0();
    
    0 讨论(0)
  • 2021-01-21 16:12

    I think you are mixing up naming and defining function pointers. I'll just point out that if you write

    void func0(void) { printf( "0\n" ); }
    void (*func0)(void);
    

    you actually have two completely unrelated objects with the same name func0. The first func0 is a function, the second func0 is a variable with type pointer-to-function.

    Assuming you declared your variable func0 globally (outside of any function), it will be automatically zero initialized, so the compiler will read your line

    void (*func0)(void);
    

    as

    void (*func0)(void) = NULL;
    

    So the variable func0 will be initialized with the value NULL, and on most systems NULL will actually be 0.

    Your debugger is now telling you that your variable func0 has the value 0x0000, which is 0. So this is really no big surprise.

    To your question regarding a "fix" - well, I assume you want a function pointer, pointing to your function func0, so you can do the following:

    void func0(void) { printf( "0\n" ); }
    void (*pFunc)(void) = func0;
    

    or even better (although on most compilers not necessary) you can write

    void (*pFunc)(void) = &func0;
    

    so you initialize your variable pFunc (I highly recommend renaming it!) to point to func0. A bit more precise: You take the adress &... of the function func0 and assign this value to your variable pFunc.

    Now you can "call" the function pointer (which means to call the function which the function pointer points to) by:

    pFunc(); //will call function func0
    
    0 讨论(0)
提交回复
热议问题