c++lambdafunction-pointers

Function pointers point to identical address values? ...sometimes


I have an array of function pointers and I want to assign simple dummy functions.

The first thing that came to my mind was using lambda. That worked pretty well. The only thing that surprised me was the fact that I get different pointer addresses when I assign them one by one, but get identical addresses when I do it in a loop.

#include <iostream>

int main()
{

    int (*ptrArr[6])(void);
    int size = sizeof(ptrArr)/sizeof(void*);

    // results in three different pointer addresses
    ptrArr[0] = [](){return 0;};
    ptrArr[1] = [](){return 0;};
    ptrArr[2] = [](){return 0;};

    // results in three identical pointer addresses
    for(int i = 3; i < size; i++)
    {
        ptrArr[i] = [](){return 0;};
    }

    for(int i = 0; i < 6; i++)
    {
        std::cout << (void*)ptrArr[i] << std::endl;
    }

    return 0;
}

Output:

00E9F810
00E9F840
00E9F870
00E9F8A0
00E9F8A0
00E9F8A0

Is there a way to get different instances of the dummy functions using the loop?

I also tried some constructions using std::function<>, but didn't get it assigned to the function pointers.


Solution

  • you can use a function template to generate multiple dummy unique functions.

    #include <iostream>
    #include <array>
    
    template <size_t N>
    int func() { return N; }
    
    int main()
    {
        constexpr size_t functions_count = 6;
    
        using func_type = int (*)(void);
        static constexpr auto ptrArr = 
          []<size_t...Ints>(std::integer_sequence<std::size_t, Ints...>)
          {
            return std::array<func_type,sizeof...(Ints)>{&func<Ints>...};
          }(std::make_integer_sequence<size_t,functions_count>{});
    
        for(int i = 0; i < functions_count; i++)
        {
            std::cout << (void*)ptrArr[i] << std::endl;
        }
    
        return 0;
    }
    
    0x58e668ea51d0
    0x58e668ea51e0
    0x58e668ea51f0
    0x58e668ea5200
    0x58e668ea5210
    0x58e668ea5220
    

    online demo

    the size needs to be known at compile time.

    i think the variadic lambda is C++20, for lower versions use a free function instead. demo