It is possible a pointer to a function inside a structure in C?
Arthur
2011-06-20 23:35:35 UTC
I'm trying to put call a function inside a structure, it is possible?
Six answers:
Cubbi
2011-06-21 03:25:06 UTC
Yes, pointers to functions can be members of a structure, in any version of C. For example:
#include
struct example
{
int (*f)(const char *);
};
int main(void)
{
struct example s;
s.f = puts;
s.f("Hello, world");
}
test: https://ideone.com/2iFTj
green meklar
2011-06-21 08:47:04 UTC
You can have a pointer to a global function. And you can store the value of that pointer inside a structure.
However, I don't think you can have a pointer to a non-static method to be called on a specific structure, since the structure doesn't change the method address, rather its own address is passed as an implicit argument to the method. Fortunately, you can simulate this behavior by making the global function refer to a global pointer and changing that pointer to point to the structure in question before making the call. You can even pass this part off to a second function (which needn't be global) so you can do the whole thing using a single function call with two arguments. It might not execute as fast but it would work.
busbee
2016-12-11 23:49:28 UTC
Your interpretation is strictly maximum ideal. The structure contains 2 factors to platforms of an same type as itself. This works because the shape is only holding assistance - and the shape length and structure (i.e. memory allocation) would not change reckoning on what the pointer factors to. The "struct node *" announcement contained in the shape only tells the compiler that the following assistance are meant to point to a struct node, so as that it may scream and shout in case you attempt to do something stupid like element it at a string (i wager you're gazing something like a binary tree?)
Embedded Engineer
2011-06-20 23:42:14 UTC
if you are trying to mimic C++, you can create functions that take as the first argument a pointer to a structure. This structure then is the "this" pointer. I have used this trick successfully on some large C programs.
Chandresh Rajkumar Manonmani.
2011-06-21 01:36:50 UTC
Yes it is possible to make it,
Refer to " 'Schaum's Outline of Theory and Problems of PROGRAMMING WITH C' by Byron S. Gottfried published by Tata Mc-Graw Hill"
anonymous
2011-06-20 23:40:54 UTC
I know it is possible in GNU C...
int somefunction(int,int);
struct mystruct{
int (*somefunction)(int,int);
};
I think it should work with any C compiler...
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.