c - 如何从 C 函数返回指针?

标签 c function pointers struct

我有一个名为 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/

相关文章:

c++ - 具有派生成员的基类的唯一指针

C++ 指针、对象等

c - gcc 编译器未通过 cmd 在 Windows 中为 C 创建 .exe 文件

c++ - 在 C++ 中没有匹配函数调用 'game_rule'

c - 将文件中的数据保存到数组中

c - 从结构中获取信息并在另一个函数中使用

javascript - 调用第二个参数而不设置第一个参数

c++ - 如何在 char 数组中插入值?

c - 在构建时更新资源文件中的 FILEVERSION

C 编程 - 如何使用 While 循环将用户的值保存在数组中