5

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?

1
  • 1
    In your code, there's no such thing as struct tMYSTRUCTURE, it's an incomplete type. All you have is an anonymous structure that also happens to be typedef'ed to tMYSTRUCTURE. See stackoverflow.com/questions/612328/… . Commented Aug 10, 2011 at 15:28

2 Answers 2

5

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;

}
Sign up to request clarification or add additional context in comments.

Comments

2

Corrected code:

#include <stdio.h>
#include <stdlib.h>

struct tMYSTRUCTURE_;

typedef struct tMYSTRUCTURE_ {
  int myint;
  void (* pCallback)(struct tMYSTRUCTURE_ *mystructure);
} tMYSTRUCTURE;


void hello(tMYSTRUCTURE *mystructure){
  puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
}

int main(void) {
  tMYSTRUCTURE mystruct;
  mystruct.pCallback = hello;

  mystruct.pCallback(&mystruct);
  return EXIT_SUCCESS;

}

Note the difference between the struct name and the typedef name. Yes, you can make them the same, but many people (myself included) find that confusing... Common practice is to keep them distinct.

Admittedly, GCC's diagnostic here was more than a little bizarre.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.