我有一个名为 playerInformation
的结构,我想从 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);
结构函数.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;
}
最佳答案
Put prototype before use. — BLUEPIXY
很久以前,SO 文档中的主题“从另一个 C 文件调用函数”就涵盖了这个问题。
在这种情况下,您需要一个定义类型struct playerInformation
的 header :
playerinfo.h
#ifndef PLAYERINFO_H_INCLUDED
#define PLAYERINFO_H_INCLUDED
struct playerInformation
{
...
};
extern struct playerInformation *findPlayerInformation(struct playerInformation *head, int playerIndex);
#endif
structFunctions.c 中的代码应包含 header :
#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;
}
关于c - 如何从 C 函数返回指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36863500/