【问题标题】:C accessing structures in different files with pointers - dereferencing pointer to incomplete typeC使用指针访问不同文件中的结构-取消引用指向不完整类型的指针
【发布时间】:2015-01-30 18:01:07
【问题描述】:

我找不到以下 C 代码的解决方案

我有3个文件如下:

1) 故事1.c

在哪里

struct Example1 
{
int first_element;           
int second_element;
...
};

int function1(Example1 *m, ...) 
{
...
m->first_element = m->second_element;
m->second_element = /* changing int data */;

return /* other integer */;
}

2) 故事1.h

在哪里

typedef struct Example1 Example1;

3) 故事2.c

在哪里

typedef struct Example2 {
Example1 *ptr;
int res2;
...
} Example2;

[...]

static void mother_function(Example2 *s)
{
int res;

res = function1(s->ptr, ...);
}

static void last_function(Example2 *s)
{
if ( ( &(s->ptr)->first_element == 10 ) &&
             ( (((*s).ptr).second_element) == 44 ) &&
             /* other conditions */ )
            s->res2 = /* new value */;
}

mother_function 调用设置 m->first_element 和 m->second_element 的 function1,例如10 和 44

现在我希望 last_function 从指针 s 开始访问这些新出生的 [in function1 of another file] 值以评估 if [从概念上讲,我想做类似的事情:

if( (s->ptr->first_element==10) && (s->ptr->second_element==44) ) then...

我尝试用 3 种方法来完成它:
1) s->ptr->first_element
2) ( &(s->ptr)->first_element == 10 )
3)( (((*s).ptr).second_element) == 44 )

编译器给了我以下错误:

1) error: dereferencing pointer to incomplete type
2) error: dereferencing pointer to incomplete type
3)error: request for member ‘second_element’ in something not a structure or union

这些消息的原因是什么?我该如何解决这个问题?

提前感谢那些愿意提供帮助的人

【问题讨论】:

    标签: c pointers data-structures structure


    【解决方案1】:

    您需要将struct Example1 { ... }; 行从story1.c 移动到story1.h(并确保story2.c 包含story1.h),以便story2.c 可以访问struct Example1 的定义。然后写s->ptr->first_element 应该可以了。

    【讨论】:

      【解决方案2】:

      只需对 Jwodder 的解决方案添加一些解释:s->ptr->first_element 正在尝试访问 struct Example1 的成员,但是,struct Example1 在story1.c 中定义,因此它对story2.c 是不可见的。

      http://en.cppreference.com/w/c/language/scope

      【讨论】:

      • 我现在才回答,因为我的办公室电脑上有这些文件......它工作得很好!感谢@jwodder 的解决方案和bl4ck5un 的解释!
      猜你喜欢
      • 1970-01-01
      • 2013-12-22
      • 2014-05-09
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      • 2014-07-06
      • 2016-07-12
      相关资源
      最近更新 更多