function pointers and pointer arguments in C
Complete noob to C
, just getting started with some goofing around, wondering how (read "if") the following is possible.
Trying to create a struct
, with a member that is a function pointer, and the function pointer points to a function that takes an argument with the same type as the aforementioned struct
. For example (mind the syntax, just getting familiar here):
typedef struct{
void (*myStructFunc)(void);
} MyStructType;
void myFunc(void){
printf("Hello world!");
}
// ...
MyStructType myStruct;
myStruct.myStructFunc = &myFunc;
myStruct.myStructFunc(); // <= Hello world!
This works fine, but when I try to introduce arguments of the MyStructType
type to the function:
typedef struct{
void (*myStructFunc)(*MyStructType); // <= parse error
} MyStructType;
void myFunc(MyStructType *myStruct){
printf("Hello world!");
}
// ...
MyStructT开发者_Python百科ype myStruct;
myStruct.myStructFunc = &myFunc;
myStruct.myStructFunc(&myStruct);
These examples are brief for obvious reasons, but they illustrate my intentions. Again, just getting my feet wet with C
so please forgive any syntactical ignorance.
Anyways, how can I achieve this? Clearly I'm doing something incorrect syntactically, or perhaps I'm trying to do something that's plain not possible.
Also note, that the reason for this is purely academic.
In your second example, the name MyStructType
isn't defined when you're declaring your function. Also, you have the *
in the wrong spot. You need to do something similar to the following:
typedef struct MyStruct {
void (*myStructFunc)(struct MyStruct *);
} MyStructType;
The parse error is coming from *MyStructType
, which appears to be a typo as you've correctly declared the struct pointer in the actual function definition.
Fixing that is still an error because, at the time of the struct
definition, the typedef
hasn't taken effect. The same problem can be illustrated (more clearly IMHO) with a linked list:
typedef struct {
node *next; // error - what is a node?
void *data;
} node; // this is where node is defined
To solve it, you need to use a named struct
:
struct node {
struct node *next;
void *data;
};
Or put the typedef
first, then define the (again named) struct
:
typedef struct node node;
struct node {
node *next;
void *data;
};
Or (if you're feeling obnoxious) just use a void *
pointer:
typedef struct {
void *next;
void *data;
} node;
The same applies to your situation.
Try:
struct MyStructType {
void (*myStructFunc)(struct MyStructType*);
};
instead. In C, structs are in their own namespace, so if you want to refer to a struct, you need to prefix the name by struct
. Your typedef
isn't seen until after you reference, which is an error. If you still want the typedef, you can do:
typedef MyStructType MyStructType_t;
精彩评论