Reputation: 1808
Presently i am using a function pointer array. But i need to extend it as an array of array of function pointers.The pseudo code is as below:
#include<stdio.h>
int AnalogValue1( int a)
{
printf("\nF: AV1 %d", a);
return 1;
}
int AnalogValue2( int a)
{
printf("\nF: AV2 %d", a);
return 1;
}
int BinaryValue1( int a)
{
printf("\nF: BV1 %d", a);
return 1;
}
int BinaryValue2( int a)
{
printf("\nF: BV2 %d", a);
return 1;
}
int ( *Read_AV_Props[] )(int a)
=
{
&AnalogValue1,
&AnalogValue2,
};
int ( *Read_BV_Props[] )(int a) =
{
&BinaryValue1,
&BinaryValue2
};
void main()
{
Read_AV_Props[0](55);
//*(Read_Ob_Props[0])(20);
}
Here need one array of array of function pointers so that it can take the address of Read_BV_Props and Read_AV_Props. And from the main code i can call that array of array of function pointers. Is this possible in C?
Upvotes: 2
Views: 448
Reputation: 21223
This is the declaration you want:
int (**myArray[])(int) = {
Read_AV_Props,
Read_BV_Props
};
This is an array of pointers to pointers to functions receiving int
and returning int
. It's not a true 2D array because Read_AV_Props
and Read_BV_Props
decay into a pointer to their first element, i.e., a pointer to pointer to function receiving int
and returning int
.
You can use it like this:
int a = (**(myArray[i]+j))(1);
Or, due to array-to-pointer decayment rule (in expressions), you could also use:
int a = (*myArray[i][j])(1);
If you want a true 2D array, you must initialize it all in one place:
int (*myArray[][])(int) = {
{ &binaryValue1, &binaryValue2 },
{ ... }
};
The usage is similar.
Or you can make an array of pointers to array of pointer to function receiving int
and returning int
with:
int (*(*myArray[])[sizeof(Read_AV_Props)/sizeof(*Read_AV_Props)])(int) = {
&Read_AV_Props,
&Read_BV_Props
};
But this assumes that Read_AV_Props
and Read_BV_Props
have the same size.
You can use this with:
int a = (*(*myArray[i])[j])(1);
Given your question, I believe the first option is what you're looking for.
Upvotes: 1
Reputation: 22104
If you need a 2D array, then you can do it like this:
#include <stdio.h>
#include <stdlib.h>
int func1(int a)
{
return a*2;
}
int func2(int a)
{
return a*3;
}
typedef int (*FunctionPtrType)(int a);
FunctionPtrType myArray[2][2] =
{
// func1, func2
{ func1, func2, },
{ func2, func1, }
};
int main()
{
int i;
printf("func1 = %p\n", func1);
printf("func2 = %p\n", func2);
for(i = 0; i < 2; i++)
{
printf("%p\n", myArray[0][i]);
printf("%p\n", myArray[1][i]);
}
return 0;
}
Upvotes: 0