2016-04-26 52 views
1

我有一個結構稱爲playerInformation,我想從我的函數C程序中返回,下面的功能是我寫的一個。如何從C中的函數返回指針?

它找到合適的結構,我可以使用printf在函數中打印細節。但是,似乎我不能返回一個指針,以便我可以在主函數內打印信息。

有了這個代碼,我得到這樣的警告:

MainTest.c: In function ‘main’: 
MainTest.c:34: warning: assignment makes pointer from integer without a cast 

MainTest.c(線33和34)

struct playerInformation *test; 
test = findPlayerInformation(head, 2); 

StructFucntions.c

struct playerInformation *findPlayerInformation(struct playerInformation *head, int playerIndex) { 
    struct playerInformation *ptr; 
     for(ptr = head; ptr != NULL; ptr = ptr->next) { 
      if(ptr->playerIndex == playerIndex) { 
       return ptr; 
      } 
     } 
    return NULL; 
} 
+0

是'findPlayerInformation'聲明(放在一個頭文件,包含在'main'定義之前maintest.c)? – purplepsycho

+1

把原型纔可使用。 – BLUEPIXY

+0

實際上它「只是」一個警告。是findPlayerInformation位於下方的主要功能還是你以前定義的函數原型? – jboockmann

回答

-4

您已經聲明struct playerInformation *ptr;,這個指針作爲findPlayerInformation()函數中的一個局部變量......所以,abov的範圍e指針僅在findPlayerInformation()函數中可用。

if(ptr->playerIndex == playerIndex) 
    return ptr; 

所以在這個語句後,控制權將轉到主函數。既然你宣佈ptr作爲一個局部變量裏面findPlayerInformation()功能,您將無法獲得ptr你在主函數預期的..

解決方案:

如果你想避免這個問題,聲明PTR作爲像靜態變量下面

static struct playerInformation *ptr; 

用來保持在整個文件中變量的作用域static關鍵字...

+3

我想你很容易混淆這個改變一個指針作爲參數傳遞。發佈的代碼很好,並且不需要靜態。此外,這不會解釋給定的編譯器警告。 – Lundin

+0

對不起。剛纔我已經看到函數調用和函數定義在不同的源文件中..所以你可以將結構指針的地址作爲另一個參數傳遞給findPlayerInformation()函數和函數內部,你可以填寫這個地址.. – sivakarthik

+0

「所以你可以傳遞結構指針的地址作爲另一個參數「這就是他正在做的。函數調用和函數定義放置在哪個文件中無關緊要。 – Lundin

1

Put prototype before use.BLUEPIXY

曾幾何時,題目是「呼籲從另一個C文件中的函數」,因此文檔中所涉及的問題。

在這種情況下,你需要定義類型struct playerInformation頭:

playerinfo.h

#ifndef PLAYERINFO_H_INCLUDED 
#define PLAYERINFO_H_INCLUDED 

struct playerInformation 
{ 
    ... 
}; 

extern struct playerInformation *findPlayerInformation(struct playerInformation *head, int playerIndex); 

#endif 

structFunctions.c的代碼應該包含頭:

#include "playerinfo.h" 

... 

struct playerInformation *findPlayerInformation(struct playerInformation *head, int playerIndex) { 
    struct playerInformation *ptr; 
     for(ptr = head; ptr != NULL; ptr = ptr->next) { 
      if(ptr->playerIndex == playerIndex) { 
       return ptr; 
      } 
     } 
    return NULL; 
} 

和主方案將包括頭太:

MainTest.c

#include "playerinfo.h" 

... 

int main(void) 
{ 
    struct playerInformation *head = ...; 
    ... 
    struct playerInformation *test; 
    test = findPlayerInformation(head, 2); 
    ... 
    return 0; 
}