【问题标题】:pointer to function, struct as parameter指向函数的指针,结构作为参数
【发布时间】:2011-10-24 04:59:36
【问题描述】:

今天再次重新输入..

结构中是指向函数的指针,在这个函数中我希望能够处理来自这个结构的数据,所以指向结构的指针作为参数给出。

这个问题的演示

#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;

}

但我收到警告

..\src\retyping.c:31:5:警告:传递参数 1 来自不兼容指针类型的“mystruct.pCallback” ..\src\retyping.c:31:5:注意:预期的 'struct tMYSTRUCTURE *' 但是 参数的类型为“struct tMYSTRUCTURE *”

预期为 'struct tMYSTRUCTURE *' 但实际上是 'struct tMYSTRUCTURE *',好笑!

任何想法如何解决它?

【问题讨论】:

  • 在你的代码中,没有struct tMYSTRUCTURE这样的东西,它是一个不完整的类型。你所拥有的只是一个 anonymous 结构,它也恰好被类型定义为tMYSTRUCTURE。见stackoverflow.com/questions/612328/…

标签: c parameters struct type-conversion function-pointers


【解决方案1】:

更正代码:

#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;

}

注意struct 名称和typedef 名称之间的区别。是的,您可以使它们相同,但许多人(包括我自己)发现这令人困惑……通常的做法是使它们保持不同。

诚然,这里 GCC 的诊断有点奇怪。

【讨论】:

    【解决方案2】:

    问题是由typedefing 结构然后使用struct 关键字和typedef'd 名称引起的。转发声明 structtypedef 可以解决问题。

    #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;
    
    }
    

    【讨论】:

      猜你喜欢
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-04
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多