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.
int size = sizeof(ptrArr)/sizeof(void*);
-- there is no guarantee thatvoid*
is the same size as a pointer to function. The usual way to do this would besizeof(ptrArr)/sizeof(*ptrArr)
. But you already know the size of your array: it's 6. If you don't throw away that information you don't have to figure out how to get it back.std::size
.