I've run into a peculiar problem. It might be best to just show you what I'm trying to do and then explain it.
typedef void functionPointerType ( struct_A * sA );
typedef struct
{
functionPointerType ** functionPointerTable;
}struct_A;
Basically, I have a structure struct_A
with a pointer to a table of function pointers, who have a parameter of type struct_A
. But I'm not sure how to get this compile, as I'm not sure how or if can forward declare this.
Anyone know how this could be achieved?
edit: minor fix in code
But you can't forward declare a typedef. Instead you have to redeclare the whole thing like so: typedef GenericValue<UTF8<char>, MemoryPoolAllocator<CrtAllocator> > Value; Ah, but I don't have any of those classes declared either.
A typedef, or a function-type alias, helps to define pointers to executable code within memory. Simply put, a typedef can be used as a pointer that references a function.
To write a forward declaration for a function, we use a function declaration statement (also called a function prototype). The function declaration consists of the function header (the function's return type, name, and parameter types), terminated with a semicolon. The function body is not included in the declaration.
In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, a constant, or a function) for which the programmer has not yet given a complete definition.
Forward declare as you suggest:
/* Forward declare struct A. */
struct A;
/* Typedef for function pointer. */
typedef void (*func_t)(struct A*);
/* Fully define struct A. */
struct A
{
func_t functionPointerTable[10];
};
For example:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct A;
typedef void (*func_t)(struct A*);
struct A
{
func_t functionPointerTable[10];
int value;
};
void print_stdout(struct A* a)
{
printf("stdout: %d\n", a->value);
}
void print_stderr(struct A* a)
{
fprintf(stderr, "stderr: %d\n", a->value);
}
int main()
{
struct A myA = { {print_stdout, print_stderr}, 4 };
myA.functionPointerTable[0](&myA);
myA.functionPointerTable[1](&myA);
return 0;
}
Output:
stdout: 4 stderr: 4
See online demo http://ideone.com/PX880w .
As others have already mentioned it is possible to add:
typedef struct A struct_A;
prior to the function pointer typedef
and full definition of struct A
if it is preferable to omit the struct
keyword.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With