首页 > 解决方案 > 通过函数传递结构指针然后访问结构数据

问题描述

我正在研究一个作为更大程序的一部分工作的函数。我的 C 指针技能有点生疏,所以我需要一些帮助。

注意:我省略了很多程序,因为它无关紧要并且可以正常工作,您只需要知道我导入了一个声明 struct 的头文件ImportedStruct,而且我无法更改函数头,所以我需要通过ImportedStruct 作为指针,函数作为指针。

我在 VS 代码中收到以下错误消息pointer to incomplete class type is not allowed

有任何想法吗?

#include "name.h"
long int *functionName(struct ImportedStruct *structName, int *irrelevant){
    int width = structName->width;
    int height = structName->height;

    // Remaining function ...
}

头文件:

struct ImportedStruct 
{ 
  int width, height;
};

标签: c

解决方案


我刚刚编译了您提供的代码

struct ImportedStruct 
{ 
  int width, height;
};

long int *functionName(struct ImportedStruct *structName, int *irrelevant){
    int width = structName->width;
    int height = structName->height;

    // Remaining function ...
    return (long int *)(width + height);
}

它编译成功。

确保包含结构定义。此外,你可以把

struct ImportedStruct 
{ 
  int width, height;
};

在你的函数定义之前。如果编译器没有给你multiple definition错误,那么头文件中不包含结构定义。


推荐阅读