簡體   English   中英

指向 function 的指針,結構為參數

[英]pointer to function, struct as parameter

今天又重新打字了。。

在結構中是指向 function 的指針,在這個 function 中,我希望能夠處理來自這個結構的數據,所以指向結構的指針作為參數給出。

這個問題的演示

#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:警告:從不兼容的指針類型傳遞 'mystruct.pCallback' 的參數 1..\src\retyping.c:31:5:'注意:預期'MYSTRUCTURE參數的類型為“struct tMYSTRUCTURE *”

預期 'struct tMYSTRUCTURE *' 但是 'struct tMYSTRUCTURE *',很有趣!

任何想法如何解決它?

問題是由typedef結構然后使用struct關鍵字和typedef的名稱引起的。 前向聲明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;

}

更正的代碼:

#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 在這里的診斷有點奇怪。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM