How to define an array of functions in C

passing 2d array to function in c
array of function pointers in c
pass char array to function c
passing dynamic array to function in c
function to print array in c
passing array by reference c++ example
passing array to function in c++
how to pass string array to function in c

I have a struct that contains a declaration like this one:

void (*functions[256])(void) //Array of 256 functions without arguments and return value

And in another function I want to define it, but there are 256 functions! I could do something like this:

struct.functions[0] = function0;
struct.functions[1] = function1;
struct.functions[2] = function2;

And so on, but this is too tiring, my question is there some way to do something like this?

struct.functions = { function0, function1, function2, function3, ..., };

EDIT: Syntax error corrected as said by Chris Lutz.

I have a struct that contains a declaration like this one:

No you don't. That's a syntax error. You're looking for:

void (*functions[256])();

Which is an array of function pointers. Note, however, that void func() isn't a "function that takes no arguments and returns nothing." It is a function that takes unspecified numbers or types of arguments and returns nothing. If you want "no arguments" you need this:

void (*functions[256])(void);

In C++, void func() does mean "takes no arguments," which causes some confusion (especially since the functionality C specifies for void func() is of dubious value.)

Either way, you should typedef your function pointer. It'll make the code infinitely easier to understand, and you'll only have one chance (at the typedef) to get the syntax wrong:

typedef void (*func_type)(void);
// ...
func_type functions[256];

Anyway, you can't assign to an array, but you can initialize an array and copy the data:

static func_type functions[256] = { /* initializer */ };
memcpy(mystruct.functions, functions, sizeof(functions));

How can I use an array of function pointers?, How should I use array of function pointers in C? How can I initialize them? share​. In C programming, creating an array for use inside a function works just like creating an array for use inside the main() function: The array is declared, it’s initialized, and its elements are used. You can also pass arrays to and from functions, where the array’s elements can be accessed or manipulated.

I had the same problem, this is my small program to test the solution. It looks pretty straightforward so I thought I'd share it for future visitors.

#include <stdio.h>

int add(int a, int b) {
    return a+b;
}

int minus(int a, int b) {
    return a-b;
}

int multiply(int a, int b) {
    return a*b;
}

typedef int (*f)(int, int);                 //declare typdef

f func[3] = {&add, &minus, &multiply};      //make array func of type f,
                                            //the pointer to a function
int main() {
    int i;
    for (i = 0; i < 3; ++i) printf("%d\n", func[i](5, 4));
    return 0;
}

How to Use Arrays and Functions Together in C Programming , You can also pass arrays to and from functions, where the array's elements can be accessed or manipulated. How to pass an array to a function. Sending an array  Multi-dimensional arrays. C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. 2: Passing arrays to functions. You can pass to the function a pointer to an array by specifying the array's name without an index. 3: Return array from a function. C allows a function to return an array. 4

You can do it dynamically... Here is a small example of a dynamic function array allocated with malloc...

#include <stdio.h>
#include <stdlib.h>

typedef void (*FOO_FUNC)(int x);

void a(int x)
{
    printf("Function a: %d\n", x);
}

void b(int x)
{
    printf("Function b: %d\n", x);
}

int main(int argc, char **argv)
{
    FOO_FUNC *pFoo = (FOO_FUNC *)malloc(sizeof(FOO_FUNC) * 2);
    pFoo[0] = &a;
    pFoo[1] = &b;

    pFoo[0](10);
    pFoo[1](20);

    return 0;
}

Array of functions, Array of Functions Labels: Arrays, Functions, Miscellaneous, Pointers In an array for(int i=0;i<5;i++) (*ptr[i])(); } // -- FUNCTIONS DEFINITION  If the size of an array is n, to access the last element, the n-1 index is used. In this example, mark [4] Suppose the starting address of mark [0] is 2120d. Then, the address of the mark [1] will be 2124d. Similarly, the address of mark [2] will be 2128d and so on. This is because the size of a float is 4 bytes.

From the top of my head and untested.

// create array of pointers to functions
void (*functions[256])(void) = {&function0, &function1, &function2, ..., };

// copy pointers to struct
int i;
for (i = 0; i < 256; i++) struct.functions[i] = functions[i];

EDIT: Corrected syntax error as said by Chris Lutz.

Pass arrays to a function in C, pass arrays (both one-dimensional and two-dimensional arrays) to a function in C programming with However, notice the use of [] in the function definition. Pass arrays to a function in C In this tutorial, you'll learn to pass arrays (both one-dimensional and multidimensional arrays) to a function in C programming with the help of examples. In C programming, you can pass en entire array to functions.

You could do that while declaring your struct instance:

function_structur fs = { struct_field1,
                         struct_field2,
                         {function0, function1, ..., function255},
                         struct_field3,
                         ... };

You cannot use this shortcut for initialize arrays after the array has been declared: if you need to do that, you'll have to do it dynamically (using a loop, a memcpy or something else).

Passing array to function in C programming with example, Just like variables, array can also be passed to a function as an argument . In this guide, we will learn how to pass the array to a function using call by value and  Functions with Array Parameters. In C, we cannot pass an array by value to a function. Whereas, an array name is a pointer (address), so we just pass an array name to a function which means to pass a pointer to the array.

Functions Pointers in C Programming with Examples, We declare and define add_array() function which takes an array address( pointer) with its elements number as parameters and returns the  However, You can pass a pointer to an array by specifying the array's name without an index. If you want to pass a single-dimension array as an argument in a function, you would have to declare function formal parameter in one of following three ways and all three declaration methods produce similar results

Passing Arrays as Function Arguments in C, Passing Arrays as Function Arguments in C - If you want to pass a single-​dimension array as an argument in a function, you would have to declare a formal  Microsoft Visual C++ 2005 supports both the managed code model that is provided by the Microsoft .NET Framework and the unmanaged native Microsoft Windows code model. Summary The sample below demonstrates building an array that contains function addresses and calling those functions.

Return array from function in C, Return array from function in C - C programming does not allow to return an of the function, so you would have to define the local variable as static variable. Passing array to function using call by reference When we pass the address of an array while calling a function then this is called function call by reference. When we pass an address as an argument, the function declaration should have a pointer as a parameter to receive the passed address.

Comments
  • Just note that the memcpy() is dangerous and non-portable, as a struct may contain any number of padding bytes. If you use memcpy() like shown here, you must verify that the compiler has no padding enabled. Typically through assert(sizeof(the_struct.functions) == sizeof(functions)) or similar.
  • That's incorrect. sizeof(some_struct) returns the size of the structure + any necessary padding. See this question for example. The usage of memcpy above is correct.
  • ..and in this case, the memcpy() isn't being used on structs anyway - it's being used to copy from one array to another, of identical size, which is fine. The fact that the destination array is a struct member is immaterial.
  • I probably should have noted that struct is a keyword, so using it as a variable name is wrong even for sample code that's never going to come near a compiler.
  • the difference between func() and func(void) is just a matter of C++ not of C, is it?
  • My bad... wrong context to this discussion... Instead, you could use typedef to define FOO_FUNC type, and then create a FOO_FUNC array and use the names as initializers...
  • sizeof(funcsFrom) is invalid here. Arrays in function parameters decay to pointers so your function is really void setFuncs(void(**funcsTo)(), void(**funcsFrom)()) with no information about the sizeof. You should a) use a macro, which would allow you to do that, or b) pass the array size as a third parameter. And if you do b, you can even c) write a wrapper macro that automatically plugs in the third argument based on the sizeof the second. Furthermore, d) use sizeof(funcsFrom) / sizeof(funcsFrom[0]) in case the types change, and e) your function is otherwise identical to memcpy.
  • @Chris thanks for the vital remarks, I've tested for 2 values only, that why I missed sizeof issue. (a) - great!; (d) - ok, but you should check first if source vector has size greater than 0; (e) - yep, but you should not forget to include string.h. See updated answer.