Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - What does this function pointer declaration mean?

Tags:

arrays

c

I am analyzing some multithreading code. In an initialization function, there is a piece of code like this:

for(i=0;i<MAX_STREAMS;i++){
    cmdStreamTaskPtr[i] = NULL;
}

I understand that syntax, but my problem is in the declaration of cmdStreamTaskPtr. It is defined in the following way, where cmdData_t is a typedef struct and MAX_STREAMS is 5.

static cmdData_t *(*cmdStreamTaskPtr[MAX_STREAMS])(void) = {[0 ... MAX_STREAMS-1] = NULL};

I have no idea what this line means. Is it a variable with a default value?

like image 556
JCMiguel Avatar asked Jun 11 '18 20:06

JCMiguel


People also ask

What is pointer declaration in C?

A pointer declaration names a pointer variable and specifies the type of the object to which the variable points. A variable declared as a pointer holds a memory address.

What do you mean by function pointer?

A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory.

How is pointer declared in C and give example?

For example, if you want a pointer to point to a variable of data type int, i.e. int var=5 then the pointer must also be of datatype 'int', i.e. int *ptr1=&var. The * symbol indicates that the variable is a pointer. To declare a variable as a pointer, you must prefix it with *.


1 Answers

cmdStreamTaskPtr is an array:

cmdStreamTaskPtr[MAX_STREAMS]

Of pointers:

*cmdStreamTaskPtr[MAX_STREAMS]

To functions that accept no arguments:

(*cmdStreamTaskPtr[MAX_STREAMS])(void)

And return a cmdData_t *:

cmdData_t *(*cmdStreamTaskPtr[MAX_STREAMS])(void)

And is static:

static cmdData_t *(*cmdStreamTaskPtr[MAX_STREAMS])(void)

That array is then initialized with NULL for all array members:

static cmdData_t *(*cmdStreamTaskPtr[MAX_STREAMS])(void) = {[0 ... MAX_STREAMS-1] = NULL};

Note that the initialization syntax [0 ... MAX_STREAMS-1] is not standard C but an extension supported by GCC. It's also redundant in this case because the array is declared as static, meaning it has static storage duration and therefore its elements are implicitly initialized to NULL if not explicitly initialized.

The use of function pointers can be made more clear with a typedef. In this situation, we can create the following typedef:

typedef cmdData_t *(*fp)(void);

This makes fp a typedef for a pointer to a function taking no arguments and returning a cmdData_t *. The array definition can then be changed to:

static fp cmdStreamTaskPtr[MAX_STREAMS];

So now it should be more clear that cmdStreamTaskPtr is an array of fp, where an fp is the previously defined function pointer.

like image 194
dbush Avatar answered Oct 20 '22 20:10

dbush