Once again today with retyping..
In structure is pointer to function, in this function I want to be able work with data from this structure, so the pointer to structure is given as parameter.
Demo of this problem
#include <stdio.h>
#include <stdlib.h>
struct tMYSTRUCTURE;
typedef struct{
int myint;
void (* pCallback)(struct tMYSTRUCTURE *mystructure);
}tMYSTRUCTURE;
void hello(struct tMYSTRUCTURE *mystructure){
puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
}
int main(void) {
tMYSTRUCTURE mystruct;
mystruct.pCallback = hello;
mystruct.pCallback(&mystruct);
return EXIT_SUCCESS;
}
But I get Warning
..\src\retyping.c:31:5: warning: passing argument 1 of 'mystruct.pCallback' from incompatible pointer type ..\src\retyping.c:31:5: note: expected 'struct tMYSTRUCTURE *' but argument is of type 'struct tMYSTRUCTURE *'
expected 'struct tMYSTRUCTURE *' but is 'struct tMYSTRUCTURE *', funny!
any Idea how to fix it?
The address of the structure is passed as an argument to the function. It is collected in a pointer to structure in function header.
Overview. As we know Pointer is a variable that stores the address of another variable of data types like int or float. Similarly, we can have a Pointer to Structures, In which the pointer variable point to the address of the user-defined data types i.e. Structures.
Structures can be passed as function arguments like all other data types. We can pass individual members of a structure, an entire structure, or, a pointer to structure to a function. Like all other data types, a structure or a structure member or a pointer to a structure can be returned by a function.
How to pass structure as an argument to the functions? Passing of structure to the function can be done in two ways: By passing all the elements to the function individually. By passing the entire structure to the function.
The problem is being caused by typedef
ing the structure and then using the struct
keyword along with the typedef
'd name. Forward declaring both the struct
and the typedef
fixes the problem.
#include <stdio.h>
#include <stdlib.h>
struct tagMYSTRUCTURE;
typedef struct tagMYSTRUCTURE tMYSTRUCTURE;
struct tagMYSTRUCTURE {
int myint;
void (* pCallback)(tMYSTRUCTURE *mystructure);
};
void hello(tMYSTRUCTURE *mystructure){
puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
}
int main(void) {
tMYSTRUCTURE mystruct;
mystruct.pCallback = hello;
mystruct.pCallback(&mystruct);
return EXIT_SUCCESS;
}
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