2016-04-26 20 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; 
}