Assigning a function pointer to an array of function pointers

In the code below, I'm trying to assign a function pointer to an array of function pointers. I get an error

error: the initialization element is not constant, and then the note indicates the beginning of initialization for 'stateTable2 [1]'.

In mainI tried to assign a pointer to a pointer to another function and no problem.

void function1 (void) // Function definition
{

}

void function2 (void) // Function definition
{

}

void (*fptr)(void) = function2;

void (*stateTable2[]) (void) = {function1,fptr};

int main()
{
    void(*fp)(void) = fptr;
    return 0;
}
+4
source share
1 answer

You cannot initialize an array with a static storage duration with a mutable object.

Either declare an array as

void (*stateTable2[]) (void) = { function1, function2 };

or move the ad

void (*stateTable2[]) (void) = {function1,fptr};

inside main, making the array as an array with automatic storage duration.

Here is a demo program.

#include <stdio.h>

void function1 (void) // Function definition
{
    printf( "Hello " );
}

void function2 (void) // Function definition
{
    puts( "World!" );
}

void (*fptr)(void) = function2;

int main(void) 
{
    void ( *stateTable2[] ) (void) = { function1, fptr };
    void(*fp)(void) = fptr;

    fp();

    for ( size_t i = 0; i < sizeof( stateTable2 ) / sizeof( *stateTable2 ); i++ )
    {
        stateTable2[i]();
    }

    return 0;
}

His conclusion

World!
Hello World!
+4

Source: https://habr.com/ru/post/1694907/


All Articles