Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer to function, struct as parameter

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?

like image 459
Meloun Avatar asked Aug 10 '11 15:08

Meloun


People also ask

Can we pass pointer to a structure to a function?

The address of the structure is passed as an argument to the function. It is collected in a pointer to structure in function header.

Can a pointer point to a struct?

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.

Can you pass a struct as a parameter in C?

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 do you pass the structure to function as an argument explain?

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.


1 Answers

The problem is being caused by typedefing 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;

}
like image 89
Praetorian Avatar answered Sep 27 '22 22:09

Praetorian