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?

Meloun
  • 13,601
  • 17
  • 64
  • 93
  • 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 http://stackoverflow.com/questions/612328/difference-between-struct-and-typedef-struct-in-c/612350#612350 . – Adam Rosenfield Aug 10 '11 at 15:28

2 Answers2

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;

}
Praetorian
  • 106,671
  • 19
  • 240
  • 328
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.

Nemo
  • 70,042
  • 10
  • 116
  • 153