开发者

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 tMYSTRUC开发者_如何学CTURE *'

expected 'struct tMYSTRUCTURE *' but is 'struct tMYSTRUCTURE *', funny!

any Idea how to fix it?


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;

}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜