How define an array of function pointers in C - c++

I've a little question.
I'm trying to define an array of function pointers dynamically with calloc.
But I don't know how to write the syntax.
Thanks a lot.

The type of a function pointer is just like the function declaration, but with "(*)" in place of the function name. So a pointer to:
int foo( int )
would be:
int (*)( int )
In order to name an instance of this type, put the name inside (*), after the star, so:
int (*foo_ptr)( int )
declares a variable called foo_ptr that points to a function of this type.
Arrays follow the normal C syntax of putting the brackets near the variable's identifier, so:
int (*foo_ptr_array[2])( int )
declares a variable called foo_ptr_array which is an array of 2 function pointers.
The syntax can get pretty messy, so it's often easier to make a typedef to the function pointer and then declare an array of those instead:
typedef int (*foo_ptr_t)( int );
foo_ptr_t foo_ptr_array[2];
In either sample you can do things like:
int f1( int );
int f2( int );
foo_ptr_array[0] = f1;
foo_ptr_array[1] = f2;
foo_ptr_array[0]( 1 );
Finally, you can dynamically allocate an array with either of:
int (**a1)( int ) = calloc( 2, sizeof( int (*)( int ) ) );
foo_ptr_t * a2 = calloc( 2, sizeof( foo_ptr_t ) );
Notice the extra * in the first line to declare a1 as a pointer to the function pointer.

I put a small example here that may help you
typedef void (*fp)(int); //Declares a type of a void function that accepts an int
void test(int i)
{
printf("%d", i);
}
int _tmain(int argc, _TCHAR* argv[])
{
fp function_array[10]; //declares the array
function_array[0] = test; //assings a function that implements that signature in the first position
function_array[0](10); //call the cuntion passing 10
}

You'd declare an array of function pointers as
T (*afp[N])();
for some type T. Since you're dynamically allocating the array, you'd do something like
T (**pfp)() = calloc(num_elements, sizeof *pfp);
or
T (**pfp)() = malloc(num_elements * sizeof *pfp);
You'd then call each function as
T x = (*pfp[i])();
or
T x = pfp[i](); // pfp[i] is implicitly dereferenced
If you want to be unorthodox, you can declare a pointer to an array of pointers to functions, and then allocate that as follows:
T (*(*pafp)[N])() = malloc(sizeof *pafp);
although you would have to deference the array pointer when making the call:
x = (*(*pafp)[i])();

typedef R (*fptr)(A1, A2... An);
where R is the return type, A1, A2... An are the argument types.
fptr* arr = calloc(num_of_elements,sizeof(fptr));

Assuming all your functions are of type void ()(void), something like this
typedef void (*fxptr)(void);
fxptr *ptr; // pointer to function pointer
ptr = malloc(100 * sizeof *ptr);
if (ptr) {
ptr[0] = fx0;
ptr[1] = fx1;
/* ... */
ptr[99] = fx100;
/* use "dynamic array" of function pointers */
free(ptr);
}

Related

C++ pointers objects difference

Can somebody explain me the difference between the following?
Those two
float *pointer[10];
float *(pointer[10]);
and those two
int(*pointer_function)();
int *pointer_function();
These two declarations
float *pointer[10];
float *(pointer[10]);
are equivalent. You can write even the following way
float *( ( pointer )[10] );
That is it is a declaration of an array of 10 pointers to float.
These declarations
int(*pointer_function)();
int *pointer_function();
are different. The first one declares a pointer to a function of type int(). The second one declares a function (not a pointer to a function) with type int *().
Here is a demonstrative program
#include <iostream>
int * pointer_function() // #1
{
static int x = 1'000'000;
return &x;
};
int f1() // #2
{
return 2'000'000;
}
int main()
{
std::cout << *pointer_function() /* calling #1 */<< '\n';
int( *pointer_function )() = f1;
std::cout << pointer_function() /* calling #2 */ << '\n';
return 0;
}
Its output is
1000000
2000000
To make more obvious the difference between the declarations you can rewrite the second declaration (that is the declaration of function) the following way
int * ( pointer_function )();
Compare it with the pointer to function declaration
int ( *pointer_function )();
Take into account that a declarator may be enclosed in parentheses.
Always keep in mind the place of Parentheses. Parentheses do not alter the type of the object, but they can alter the binding of complex declarators.
From above code snippet:
float *pointer[10];// Array of 10 pointer to float
float *(pointer[10]); //bracket around array of 10 pointer to float, So same as above
int(*pointer_function)(); // function pointer to achieve callbacks
int * pointer_function(); // function to integer pointer

Dynamically allocating arrays of structs in c++. Why is the array getting overwritten? [duplicate]

I need to do a simple thing, which I used to do many times in Java, but I'm stuck in C (pure C, not C++). The situation looks like this:
int *a;
void initArray( int *arr )
{
arr = malloc( sizeof( int ) * SIZE );
}
int main()
{
initArray( a );
// a is NULL here! what to do?!
return 0;
}
I have some "initializing" function, which SHOULD assign a given pointer to some allocated data (doesn't matter). How should I give a pointer to a function in order to this pointer will be modified, and then can be used further in the code (after that function call returns)?
You need to adjust the *a pointer, this means you need to pass a pointer to the *a. You do that like this:
int *a;
void initArray( int **arr )
{
*arr = malloc( sizeof( int ) * SIZE );
}
int main()
{
initArray( &a );
return 0;
}
You are assigning arr by-value inside initArray, so any change to the value of arr will be invisible to the outside world. You need to pass arr by pointer:
void initArray(int** arr) {
// perform null-check, etc.
*arr = malloc(SIZE*sizeof(int));
}
...
initArray(&a);

What does the following C++statement mean

There is a statement I saw in an C++ interview test today:
int (*(*fb)(int, char*))[2];
I have no idea what this declaration could mean. It looks much like function pointer but first star and square braces spoil everything.
Visual Studio decodes fb's type as following int[2] * (int, char *) *, which still looks like a bit cryptic.
If we simplify declaration than everything looks clear
int(*(*fa)(int, char*));
int* func(int, char*)
{
return 0;
}
// now we can assign func to fa
fa = func;
Any ideas?
fb is a function pointer of the following signature:
The function takes two parameters: int and char*
The function returns a pointer to an array of two int, which has the type int(*)[2]
Usually, because of the cryptic syntax of function pointers, array pointers and such stuff, you should use typedefs or type aliases (the new using-syntax) to make it clearer step by step:
using int2 = int[2];
using int2ptr = int2*;
using fb = int2ptr(int, char*);
Proof
Also, instead of returning arrays, you could consider returning a std::vector or std::array; instead of passing char pointers you could consider std::string, and instead of using function pointers you could consider std::function. All these are "coulds", since every "raw type" has its reason to exist, but the reasons are very limited.
It is a definition of pointer to function that has two parameters, one of type int and other of type char *, and returns pointer to array of type int[2].
Here is a simplified demonstrative program. I have only changed the second parameter to type const char *
#include <iostream>
int(*f( int x, const char *s ))[2]
{
static int a[2] = { x, *s };
return &a;
}
int main()
{
int (*(*fb)(int, const char*))[2] = f;
auto p = fb( 10, "A" );
std::cout << ( *p )[0] << '\t' << ( char )( *p )[1] << std::endl;
return 0;
}
The output is
10 A
Colleague of mine have just sent an answer:
int (*(*fb)(int, char*))[2];
int(*(returnArray(int, char*)))[2]
{
static int tab[2];
return &tab;
}
// finally we have it
fb = returnArray;
I have no idea who can use this and for what purpose

What does *& mean in a function parameter

If I have a function that takes int *&, what does it means? How can I pass just an int or a pointer int to that function?
function(int *& mynumber);
Whenever I try to pass a pointer to that function it says:
error: no matching function for call to 'function(int *)'
note: candidate is 'function(int *&)'
It's a reference to a pointer to an int. This means the function in question can modify the pointer as well as the int itself.
You can just pass a pointer in, the one complication being that the pointer needs to be an l-value, not just an r-value, so for example
int myint;
function(&myint);
alone isn't sufficient and neither would 0/NULL be allowable, Where as:
int myint;
int *myintptr = &myint;
function(myintptr);
would be acceptable. When the function returns it's quite possible that myintptr would no longer point to what it was initially pointing to.
int *myintptr = NULL;
function(myintptr);
might also make sense if the function was expecting to allocate the memory when given a NULL pointer. Check the documentation provided with the function (or read the source!) to see how the pointer is expected to be used.
Simply: a reference to a pointer.
In C, without references, the traditional way to "relocate" a pointer, is to pass a pointer to a pointer:
void c_find(int** p, int val); /* *p will point to the node with value 'val' */
In C++, this can be expressed by the reference syntax, to avoid the awkward double dereference.
void cpp_find(int*& p, int val); // p will point to the node with value 'val'
It means a reference to a pointer to an int. In other words, the function can change the parameter to point to something else.
To pass a variable in, just pass an int*. As awoodland points out, what's passed in must be an l-value.
Edit:
To build on awoodland's example:
#include <iostream>
void foo(int*& var)
{
delete var;
var = new int;
}
int main(int argc, char* argv[])
{
int* var = NULL;
std::cout << var << std::endl;
foo(var); // this function can/will change the value of the pointer
std::cout << var << std::endl;
delete var;
return 0;
}
function takes a single parameter, mynumber which is a reference to a pointer to an int.
This is useful when you need to pass a pointer to a function, and that function might change the pointer. For example, if you function is implemented like this:
function(int*& mynumber)
{
if( !mynumber )
mynumber = new int;
*mynumber = 42;
}
...Then something like this might happen in the calling code:
int main()
{
int* mynumber = 0;
function(mynumber); // function will change what "mynumber" points to
cout << *mynumber;
return 0;
}
This is a reference to a pointer to int - you would have to pass in the address of an int to this function, and be aware that the function could change the pointer through the reference.
Dumb example:
void func(int*& iref)
{
iref = new int;
}
int main()
{
int i(0);
int* pi(&i);
func(pi);
// pi no longer equal to &i
return 0;
}

Difference between [square brackets] and *asterisk

If you write a C++ function like
void readEmStar( int *arrayOfInt )
{
}
vs a C++ function like:
void readEmSquare( int arrayOfInt[] )
{
}
What is the difference between using [square brackets] vs *asterisk, and does anyone have a style guide as to which is preferrable, assuming they are equivalent to the compiler?
For completeness, an example
void readEmStar( int *arrayOfInt, int len )
{
for( int i = 0 ; i < len; i++ )
printf( "%d ", arrayOfInt[i] ) ;
puts("");
}
void readEmSquare( int arrayOfInt[], int len )
{
for( int i = 0 ; i < len; i++ )
printf( "%d ", arrayOfInt[i] ) ;
puts("");
}
int main()
{
int r[] = { 2, 5, 8, 0, 22, 5 } ;
readEmStar( r, 6 ) ;
readEmSquare( r, 6 ) ;
}
When you use the type char x[] instead of char *x without initialization, you can consider them the same. You cannot declare a new type as char x[] without initialization, but you can accept them as parameters to functions. In which case they are the same as pointers.
When you use the type char x[] instead of char *x with initialization, they are completely 100% different.
Example of how char x[] is different from char *x:
char sz[] = "hello";
char *p = "hello";
sz is actually an array, not a pointer.
assert(sizeof(sz) == 6);
assert(sizeof(sz) != sizeof(char*));
assert(sizeof(p) == sizeof(char*));
Example of how char x[] is the same as char *x:
void test1(char *p)
{
assert(sizeof(p) == sizeof(char*));
}
void test2(char p[])
{
assert(sizeof(p) == sizeof(char*));
}
Coding style for passing to functions:
It really doesn't matter which one you do. Some people prefer char x[] because it is clear that you want an array passed in, and not the address of a single element.
Usually this is already clear though because you would have another parameter for the length of the array.
Further reading:
Please see this post entitled Arrays are not the same as pointers!
C++ Standard 13.1.3
— Parameter declarations that differ
only in a pointer * versus an array []
are equivalent. That is, the array
declaration is adjusted to become a
pointer declaration (8.3.5). Only the
second and subsequent array dimensions
are significant in parameter types
(8.3.4). [Example:
int f(char*);
int f(char[]); // same as f(char*);
int f(char[7]); // same as f(char*);
int f(char[9]); // same as f(char*);
int g(char(*)[10]);
int g(char[5][10]); // same as g(char(*)[10]);
int g(char[7][10]); // same as g(char(*)[10]);
int g(char(*)[20]); // different from g(char(*)[10]);
—end example]
There is no difference between your two codes, apart from the different style obviously. In both cases the array is passed by reference and not by value, as function parameters type *x and type x[] are semantically the same.
On the style question I'll stick my neck out and say int *arrayOfInt is better. Which ever syntax you use you are passing a pointer and the type should make that clear.
This is just my opinion.
The two expressions are equivalent. They each evaluate to the address of the first element of the array arrayOfInt.