Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array as function with arguments?

I'm trying to learn c, so I tried reading some source code.
But I have no idea what this might mean:

static const char*(*const functab[])(void)={
        ram,date
};

The first part, static const char* is fine, as it seems to be a function (has an argument of type void), static should mean that it is only visible in this file and const char* should mean that the value cannot be changed but the address can be changed.
But in that case, it doesn't make sense after the last part following the function name, as it was the case with

static const char * date(void);
static const char * ram(void);

Instead of the function name there is (*const functab[]), a const array called functab containing addresses?
Is this some kind of wrapping function containing the functions ram and date? Some alternative way of declaring arrays?

like image 698
gw0 Avatar asked Dec 13 '16 06:12

gw0


People also ask

Can an array be a function argument?

A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name. In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun(). The below example demonstrates the same.

How do you pass an array as functions arguments?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.

What do you mean by array as a function argument?

If we pass an entire array to a function, all the elements of the array can be accessed within the function. Single array elements can also be passed as arguments. This can be done in exactly the same way as we pass variables to a function.

Can one dimensional array be passed as function arguments in C language?

An array can be passed to functions in C using pointers by passing reference to the base address of the array, and similarly, a multidimensional array can also be passed to functions in C.


2 Answers

functab is an array of function pointers (array of const function pointers, to be exact), which returns const char* and accepts no arguments.

Later,

 ... = { ram, date };

is a brace-enclosed initializer list which serves as the initializer for the array.

like image 84
Sourav Ghosh Avatar answered Oct 02 '22 15:10

Sourav Ghosh


This is the way to define array of function pointers in C. So instead of calling function as ram(), using this array you can call it by (* functab[1]).

Below discussion has good examples of array of function pointer: How can I use an array of function pointers?

like image 30
Dipti Shiralkar Avatar answered Oct 02 '22 13:10

Dipti Shiralkar