I want to create an array of void function pointers, allocate its memory and assign to the array adresses of function I want it to contain. While declaring an array, you are able to assign to it elements in a form of list in brackets like this:
const char *array[NUM_OF_ELEMENTS] = {"foo1", "boo2", "foo2", "boo2"}; // etc.
Alright. I have declared an array of pointers to void functions as it is shown below:
void (*pointerArray)(void) = malloc(NUM_OF_ELEMENTS * sizeof(*pointerArray));
My question is: Is it possible to first declare a function and simultaneously allocate its memory, and then use "bracket form" of assigning adresses on my pointerArray so it actually points to any function? More general question: Is there any way to do it quick way or I have to do this the long way as shown here:
pointerArray[0] = func1;
pointerArray[1] = func2;
pointerArray[2] = func3; // etc.
3 Answers 3
With NUM_OF_ELEMENTS being a constant value, there doesn't seem to be any good reason for you to allocate this array dynamically, so you may as well allocate it statically and initialize it upon declaration:
typedef void(*func_ptr)(void);
func_ptr func_ptr_array[] = {func1,func2,func3};
2 Comments
You can use the stack:
void (*p_stack[])(void) = { func1 , func2 } ;
Or in the case you really need to use malloc, first allocate your array with malloc and the another one on the stack and copy:
void (*p_stack[NUM_OF_ELEMENTS])(void) = { func1 , func2 } ;
void (**pointerArray)(void) = malloc(NUM_OF_ELEMENTS * sizeof(*pointerArray));
memcpy( pointerArray , p_stack , sizeof( p_stack) ) ;
The initialization is done on the p_stack array, and is then copied to the allocated array.
Comments
void (*pointerArray)(void) is a declaration of a function pointer. *pointerArray is a function. Functions don't have sizes and you cannot allocate them and there is no such thing as an array of functions and you cannot assign or copy functions.
What you need is an array of function pointers. To make things easier let's notate it with a typedef:
typedef void vfun(void);
typedef vfun* vfunp;
vfunp* pointerArray = malloc (NUM_OF_ELEMENTS * sizeof(vfunp));
pointerArray[0] = func1;
pointerArray[1] = func2;
pointerArray[2] = func3; // etc.
Or you can have a statically allocated array if you want:
vfunp pointerArray[] = { func1, func2, func3 };
2 Comments
(*pointerArray)(void) becomes an array when I'm allocating NUM_OF_ELEMENTS blocks each of size sizeof(*pointerArray). Otherwise I could just write void (*pointerArray[NUM_OF_ELEMENTS])(void);. By the way, doesn't storing pointers to functions in an array take some memory space? I feel green about that to be honest.void (*pointerArray)(void) is a pointer to a function. A pointer to something can point to the first element of an array of that something. So you would want to make pointerArray to point to an array of functions, but there are no arrays of functions, with malloc or otherwise.
callocfunction).